repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
insomnium
github_2023
ArchGPT
typescript
_fixOldGitURIs
async function _fixOldGitURIs(doc: GitRepository) { if (!doc.uriNeedsMigration) { return; } if (!doc.uri.endsWith('.git')) { doc.uri += '.git'; } doc.uriNeedsMigration = false; await database.update(doc); console.log(`[fix] Fixed git URI for ${doc._id}`); }
// Append .git to old git URIs to mimic previous isomorphic-git behaviour
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/database.ts#L846-L858
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
renderSubContext
async function renderSubContext( subObject: Record<string, any>, subContext: Record<string, any>, ) { const keys = _getOrderedEnvironmentKeys(subObject); for (const key of keys) { /* * If we're overwriting a string, try to render it first using the same key from the base * environment to support same-variable recursion. This allows for the following scenario: * * base: { base_url: 'google.com' } * obj: { base_url: '{{ base_url }}/foo' } * final: { base_url: 'google.com/foo' } * * A regular Object.assign would yield { base_url: '{{ base_url }}/foo' } and the * original base_url of google.com would be lost. */ if (Object.prototype.toString.call(subObject[key]) === '[object String]') { const isSelfRecursive = subObject[key].match(`{{ ?${key}[ |][^}]*}}`); if (isSelfRecursive) { // If we're overwriting a variable that contains itself, make sure we // render it first subContext[key] = await render( subObject[key], subContext, // Only render with key being overwritten null, KEEP_ON_ERROR, 'Environment', ); } else { // Otherwise it's just a regular replacement subContext[key] = subObject[key]; } } else if (Object.prototype.toString.call(subContext[key]) === '[object Object]') { // Context is of Type object, Call this function recursively to handle nested objects. subContext[key] = await renderSubContext(subObject[key], subContext[key]); } else { // For all other Types, add the Object to the Context. subContext[key] = subObject[key]; } } return subContext; }
// Made the rendering into a recursive function to handle nested Objects
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/render.ts#L116-L161
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getKeySource
function getKeySource(subObject: string | Record<string, any>, inKey: string, inSource: string) { // Add key to map if it's not root if (inKey) { keySource[templatingUtils.normalizeToDotAndBracketNotation(inKey)] = inSource; } // Recurse down for Objects and Arrays const typeStr = Object.prototype.toString.call(subObject); if (typeStr === '[object Object]') { for (const key of Object.keys(subObject)) { // @ts-expect-error -- mapping unsoundness getKeySource(subObject[key], templatingUtils.forceBracketNotation(inKey, key), inSource); } } else if (typeStr === '[object Array]') { for (let i = 0; i < subObject.length; i++) { // @ts-expect-error -- mapping unsoundness getKeySource(subObject[i], templatingUtils.forceBracketNotation(inKey, i), inSource); } } }
// Function that gets Keys and stores their Source location
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/render.ts#L332-L352
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
_nunjucksSortValue
function _nunjucksSortValue(v: string) { return v?.match?.(/({{|{%)/) ? 2 : 1; }
/** * Sort the keys that may have Nunjucks last, so that other keys get * defined first. Very important if env variables defined in same obj * (eg. {"foo": "{{ bar }}", "bar": "Hello World!"}) * * @param v * @returns {number} */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/render.ts#L564-L566
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
exponentialBackOff
const exponentialBackOff = async (url: string, init: RequestInit, retries = 0): Promise<Response> => { try { const response = await net.fetch(url, init); if (response.status === 502 && retries < 5) { retries++; await delay(retries * 200); return exponentialBackOff(url, init, retries); } if (!response.ok) { console.log(`Response not OK: ${response.status} for ${url}`); } return response; } catch (err) { throw err; } };
// internal request (insomniaFetch)
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/insomniaFetch.ts#L24-L39
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
mockTypeFields
function mockTypeFields(type: Type, stackDepth: StackDepth): object { if (stackDepth.incrementAndCheckIfOverMax(`$type.${type.name}`)) { return {}; } const fieldsData: { [key: string]: any } = {}; if (!type.fieldsArray) { return fieldsData; } return type.fieldsArray.reduce((data, field) => { const resolvedField = field.resolve(); if (resolvedField.parent !== resolvedField.resolvedType) { if (resolvedField.repeated) { data[resolvedField.name] = [mockField(resolvedField, stackDepth)]; } else { data[resolvedField.name] = mockField(resolvedField, stackDepth); } } return data; }, fieldsData); }
/** * Mock a field type */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/ipc/automock.ts#L80-L102
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
mockEnum
function mockEnum(enumType: Enum): number { const enumKey = Object.keys(enumType.values)[0]; return enumType.values[enumKey]; }
/** * Mock enum */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/ipc/automock.ts#L107-L111
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
mockField
function mockField(field: Field, stackDepth: StackDepth): any { if (stackDepth.incrementAndCheckIfOverMax(`$field.${field.name}`)) { return {}; } if (field instanceof MapField) { return mockMapField(field, stackDepth); } if (field.resolvedType instanceof Enum) { return mockEnum(field.resolvedType); } if (isProtoType(field.resolvedType)) { return mockTypeFields(field.resolvedType, stackDepth); } const mockPropertyValue = mockScalar(field.type, field.name); if (mockPropertyValue === null) { const resolvedField = field.resolve(); return mockField(resolvedField, stackDepth); } else { return mockPropertyValue; } }
/** * Mock a field */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/ipc/automock.ts#L116-L142
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
interpretMockViaFieldName
function interpretMockViaFieldName(fieldName: string): string { const fieldNameLower = fieldName.toLowerCase(); if (fieldNameLower.startsWith('id') || fieldNameLower.endsWith('id')) { return v4(); } return 'Hello'; }
/** * Tries to guess a mock value from the field name. * Default Hello. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/ipc/automock.ts#L232-L240
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
waitForStreamToFinish
async function waitForStreamToFinish(stream: Readable | Writable) { return new Promise<void>(resolve => { // @ts-expect-error -- access of internal values that are intended to be private. We should _not_ do this. if (stream._readableState?.finished) { return resolve(); } // @ts-expect-error -- access of internal values that are intended to be private. We should _not_ do this. if (stream._writableState?.finished) { return resolve(); } stream.on('close', () => { resolve(); }); stream.on('error', () => { resolve(); }); }); }
// NOTE: legacy, suspicious, could be simplified
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/network/libcurl-promise.ts#L439-L458
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateCookieId
function migrateCookieId(cookieJar: CookieJar) { for (const cookie of cookieJar.cookies) { if (!cookie.id) { cookie.id = Math.random().toString().replace('0.', ''); } } return cookieJar; }
/** Ensure every cookie has an ID property */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/cookie-jar.ts#L97-L105
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateBody
function migrateBody(request: Request) { if (request.body && typeof request.body === 'object') { return request; } // Second, convert all existing urlencoded bodies to new format const contentType = getContentTypeFromHeaders(request.headers) || ''; const wasFormUrlEncoded = !!contentType.match(/^application\/x-www-form-urlencoded/i); if (wasFormUrlEncoded) { // Convert old-style form-encoded request bodies to new style request.body = { mimeType: CONTENT_TYPE_FORM_URLENCODED, params: deconstructQueryStringToParams(typeof request.body === 'string' ? request.body : '', false), }; } else if (!request.body && !contentType) { request.body = {}; } else { const rawBody: string = typeof request.body === 'string' ? request.body : ''; request.body = typeof contentType !== 'string' ? { text: rawBody, } : { mimeType: contentType.split(';')[0], text: rawBody, }; } return request; }
// ~~~~~~~~~~ //
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/request.ts#L324-L352
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateWeirdUrls
function migrateWeirdUrls(request: Request) { // Some people seem to have requests with URLs that don't have the indexOf // function. This should clear that up. This can be removed at a later date. if (typeof request.url !== 'string') { request.url = ''; } return request; }
/** * Fix some weird URLs that were caused by an old bug * @param request */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/request.ts#L358-L366
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateAuthType
function migrateAuthType(request: Request) { const isAuthSet = request.authentication && request.authentication.username; if (isAuthSet && !request.authentication.type) { request.authentication.type = AUTH_BASIC; } return request; }
/** * Ensure the request.authentication.type property is added * @param request */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/request.ts#L372-L380
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateEnsureHotKeys
function migrateEnsureHotKeys(settings: Settings): Settings { const defaultHotKeyRegistry = hotkeys.newDefaultRegistry(); // Remove any hotkeys that are no longer in the default registry const hotKeyRegistry = (Object.keys(settings.hotKeyRegistry) as KeyboardShortcut[]).reduce((newHotKeyRegistry, key) => { if (key in defaultHotKeyRegistry) { newHotKeyRegistry[key] = settings.hotKeyRegistry[key]; } return newHotKeyRegistry; }, {} as Settings['hotKeyRegistry']); settings.hotKeyRegistry = { ...defaultHotKeyRegistry, ...hotKeyRegistry }; return settings; }
/** * Ensure map is updated when new hotkeys are added */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/settings.ts#L123-L137
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
_migrateEnsureName
function _migrateEnsureName(workspace: Workspace) { if (typeof workspace.name !== 'string') { workspace.name = 'My Workspace'; } return workspace; }
/** * Ensure workspace has a valid String name. Due to real-world bug reports, we know * this happens (and it causes problems) so this migration will ensure that it is * corrected. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/workspace.ts#L123-L129
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
_migrateScope
function _migrateScope(workspace: MigrationWorkspace) { if (workspace.scope === WorkspaceScopeKeys.design || workspace.scope === WorkspaceScopeKeys.collection) { return workspace as Workspace; } if (workspace.scope === 'designer' || workspace.scope === 'spec') { workspace.scope = WorkspaceScopeKeys.design; } else { workspace.scope = WorkspaceScopeKeys.collection; } return workspace as Workspace; }
/** * Ensure workspace scope is set to a valid entry */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/workspace.ts#L138-L148
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
toSchema
const toSchema = <T>(obj: T): Schema<T> => { const cloned = clone(obj); const output: Partial<Schema<T>> = {}; // @ts-expect-error -- mapping unsoundness Object.keys(cloned).forEach(key => { // @ts-expect-error -- mapping unsoundness output[key] = () => cloned[key]; }); return output as Schema<T>; };
// move into fluent-builder
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/__schemas__/model-schemas.ts#L13-L24
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getExistingAccessTokenAndRefreshIfExpired
async function getExistingAccessTokenAndRefreshIfExpired( requestId: string, authentication: AuthTypeOAuth2, forceRefresh: boolean, ): Promise<OAuth2Token | null> { const token: OAuth2Token | null = await models.oAuth2Token.getByParentId(requestId); if (!token) { return null; } const expiresAt = token.expiresAt || Infinity; const isExpired = Date.now() > expiresAt; if (!isExpired && !forceRefresh) { return token; } if (!token.refreshToken) { return null; } let params = [ { name: 'grant_type', value: 'refresh_token' }, { name: 'refresh_token', value: token.refreshToken }, ...insertAuthKeyIf('scope', authentication.scope), ]; const headers = []; if (authentication.credentialsInBody) { params = [ ...params, ...insertAuthKeyIf('client_id', authentication.clientId), ...insertAuthKeyIf('client_secret', authentication.clientSecret), ]; } else { headers.push(getBasicAuthHeader(authentication.clientId, authentication.clientSecret)); } const response = await sendAccessTokenRequest(requestId, authentication, params, []); const statusCode = response.statusCode || 0; const bodyBuffer = models.response.getBodyBuffer(response); if (statusCode === 401) { // If the refresh token was rejected due an unauthorized request, we will // return a null access_token to trigger an authentication request to fetch // brand new refresh and access tokens. const old = await models.oAuth2Token.getOrCreateByParentId(requestId); models.oAuth2Token.update(old, transformNewAccessTokenToOauthModel({ access_token: null })); return null; } const isSuccessful = statusCode >= 200 && statusCode < 300; const hasBodyAndIsError = bodyBuffer && statusCode === 400; if (!isSuccessful) { if (hasBodyAndIsError) { const body = tryToParse(bodyBuffer.toString()); // If the refresh token was rejected due an oauth2 invalid_grant error, we will // return a null access_token to trigger an authentication request to fetch // brand new refresh and access tokens. if (body?.error === 'invalid_grant') { console.log(`[oauth2] Refresh token rejected due to invalid_grant error: ${body.error_description}`); const old = await models.oAuth2Token.getOrCreateByParentId(requestId); models.oAuth2Token.update(old, transformNewAccessTokenToOauthModel({ access_token: null })); return null; } } throw new Error(`[oauth2] Failed to refresh token url=${authentication.accessTokenUrl} status=${statusCode}`); } guard(bodyBuffer, `[oauth2] No body returned from ${authentication.accessTokenUrl}`); const data = tryToParse(bodyBuffer.toString()); if (!data) { return null; } const old = await models.oAuth2Token.getOrCreateByParentId(requestId); return models.oAuth2Token.update(old, transformNewAccessTokenToOauthModel({ ...data, refresh_token: data.refresh_token || token.refreshToken, })); }
// 1. get token from db and return if valid
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/network/o-auth-2/get-token.ts#L175-L249
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
GitVCS.canPush
async canPush(gitCredentials?: GitCredentials | null): Promise<boolean> { const branch = await this.getBranch(); const remote = await this.getRemote('origin'); if (!remote) { throw new Error('Remote not configured'); } const remoteInfo = await git.getRemoteInfo({ ...this._baseOpts, ...gitCallbacks(gitCredentials), forPush: true, url: remote.url, }); const logs = (await this.log({ depth: 1 })) || []; const localHead = logs[0].oid; const remoteRefs = remoteInfo.refs || {}; const remoteHeads = remoteRefs.heads || {}; const remoteHead = remoteHeads[branch]; if (localHead === remoteHead) { return false; } return true; }
/** * Check to see whether remote is different than local. This is here because * when pushing with isomorphic-git, if the HEAD of local is equal the HEAD * of remote, it will fail with a non-fast-forward message. * * @param gitCredentials * @returns {Promise<boolean>} */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/git/git-vcs.ts#L339-L364
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getGitLabConfig
const getGitLabConfig = async () => { const { INSOMNIA_GITLAB_REDIRECT_URI, INSOMNIA_GITLAB_CLIENT_ID } = env; // Validate and use the environment variables if provided if ( (INSOMNIA_GITLAB_REDIRECT_URI && !INSOMNIA_GITLAB_CLIENT_ID) || (!INSOMNIA_GITLAB_REDIRECT_URI && INSOMNIA_GITLAB_CLIENT_ID) ) { throw new Error('GitLab Client ID and Redirect URI must both be set.'); } if (INSOMNIA_GITLAB_REDIRECT_URI && INSOMNIA_GITLAB_CLIENT_ID) { return { clientId: INSOMNIA_GITLAB_CLIENT_ID, redirectUri: INSOMNIA_GITLAB_REDIRECT_URI, }; } // Otherwise fetch the config for the GitLab API return window.main.axiosRequest({ url: getApiBaseURL() + '/v1/oauth/gitlab/config', method: 'GET', }).then(({ data }) => { return { clientId: data.applicationId, redirectUri: data.redirectUri, }; }); };
// Warning: As this is a global fetch we need to handle errors, retries and caching
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/git/gitlab-oauth-provider.ts#L10-L38
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
_generateSnapshotID
function _generateSnapshotID(parentId: string, backendProjectId: string, state: SnapshotState) { const hash = crypto.createHash('sha1').update(backendProjectId).update(parentId); const newState = [...state].sort((a, b) => (a.blob > b.blob ? 1 : -1)); for (const entry of newState) { hash.update(entry.blob); } return hash.digest('hex'); }
/** Generate snapshot ID from hashing parent, backendProject, and state together */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/vcs/vcs.ts#L1513-L1522
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
action
const action = () => pullBackendProject({ vcs, backendProject, remoteProjects: [] });
// Act
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/vcs/__tests__/pull-backend-project.test.ts#L146-L146
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
action
const action = async () => await interceptAccessError({ action: 'action', callback: () => { throw new Error('DANGER! invalid access to the fifth dimensional nebulo 9.'); }, resourceName: 'resourceName', resourceType: 'resourceType', }) as Error;
// Arrange
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/vcs/__tests__/util.test.ts#L1007-L1014
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
action
const action = async () => await interceptAccessError({ action: 'action', callback: () => { throw new Error(message); }, resourceName: 'resourceName', resourceType: 'resourceType', }) as Error;
// Act
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/vcs/__tests__/util.test.ts#L1027-L1034
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
SingleErrorBoundary.UNSAFE_componentWillReceiveProps
UNSAFE_componentWillReceiveProps(nextProps: Props) { const { error, info } = this.state; const invalidationKeyChanged = nextProps.invalidationKey !== this.props.invalidationKey; const isErrored = error !== null || info !== null; const shouldResetError = invalidationKeyChanged && isErrored; if (shouldResetError) { this.setState({ error: null, info: null, }); } }
// eslint-disable-next-line camelcase
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/error-boundary.tsx#L28-L40
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
persistState
const persistState = () => { if (uniquenessKey && codeMirror.current) { editorStates[uniquenessKey] = { scroll: codeMirror.current.getScrollInfo(), selections: codeMirror.current.listSelections(), cursor: codeMirror.current.getCursor(), history: codeMirror.current.getHistory(), marks: codeMirror.current.getAllMarks() .filter(mark => mark.__isFold) .map((mark): Partial<CodeMirror.MarkerRange> => { const markerRange = mark.find(); return markerRange && 'from' in markerRange ? markerRange : { from: undefined, to: undefined, }; }), }; } };
// NOTE: maybe we don't need this anymore?
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/code-editor.tsx#L384-L402
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
preventDefault
const preventDefault = (_: CodeMirror.Editor, event: Event) => type?.toLowerCase() === 'password' && event.preventDefault();
// Prevent these things if we're type === "password"
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/one-line-editor.tsx#L169-L169
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
hint
function hint(cm: CodeMirror.Editor, options: ShowHintOptions) { // Add type to all things (except constants, which need to convert to an object) const variablesToMatch: VariableCompletionItem[] = (options.variables || []).map(v => ({ ...v, type: TYPE_VARIABLE })); const snippetsToMatch: SnippetCompletionItem[] = (options.snippets || []).map(v => ({ ...v, type: TYPE_SNIPPET })); const tagsToMatch: TagCompletionItem[] = (options.tags || []).map(v => ({ ...v, type: TYPE_TAG })); const constantsToMatch: ConstantCompletionItem[] = (options.constants || []).map(s => ({ name: s, value: s, displayValue: '', // No display since name === value type: TYPE_CONSTANT, })); // Get the text from the cursor back const cur = cm.getCursor(); const pos = CodeMirror.Pos(cur.line, cur.ch - MAX_HINT_LOOK_BACK); const previousText = cm.getRange(pos, cur); // See if we're allowed matching tags, vars, or both const isInVariable = previousText.match(AFTER_VARIABLE_MATCH); const isInTag = previousText.match(AFTER_TAG_MATCH); const isInNothing = !isInVariable && !isInTag; const allowMatchingVariables = isInNothing || isInVariable; const allowMatchingTags = isInNothing || isInTag; const allowMatchingConstants = isInNothing; // Define fallback segment to match everything or nothing const fallbackSegment = options.showAllOnNoMatch ? '' : '__will_not_match_anything__'; // See if we're completing a variable name const nameMatch = previousText.match(NAME_MATCH); const nameMatchLong = previousText.match(NAME_MATCH_FLEXIBLE); const nameSegment = nameMatch ? nameMatch[0] : fallbackSegment; const nameSegmentLong = nameMatchLong ? nameMatchLong[0] : fallbackSegment; const nameSegmentFull = previousText; // Actually try to match the list of things let lowPriorityMatches: Hint[] = []; let highPriorityMatches: Hint[] = []; const modeOption = cm.getOption('mode') ?? 'unknown'; let mode = 'unknown'; if (typeof modeOption === 'string') { mode = modeOption; } else if (isNunjucksMode(modeOption)) { mode = modeOption.baseMode; } // Match variables if (allowMatchingVariables) { const sortVariableCompletionHints = getCompletionHints(variablesToMatch, nameSegment, TYPE_VARIABLE, MAX_VARIABLES); lowPriorityMatches = [...lowPriorityMatches, ...sortVariableCompletionHints]; const longVariableCompletionHints = getCompletionHints(variablesToMatch, nameSegmentLong, TYPE_VARIABLE, MAX_VARIABLES); highPriorityMatches = [...highPriorityMatches, ...longVariableCompletionHints]; } // Match constants if (allowMatchingConstants) { const cur = cm.getCursor(); const token = cm.getTokenAt(cur); if (mode === 'graphql-variables') { const segment = token.string .trim() .replace(/^{?"?/, '') // Remove leading '{' and spaces .replace(/"?}?$/, ''); // Remove trailing quotes and spaces if (token.type === 'variable') { // We're inside a JSON key const constantCompletionHints = getCompletionHints(constantsToMatch, segment, TYPE_CONSTANT, MAX_CONSTANTS); highPriorityMatches = [...highPriorityMatches, ...constantCompletionHints]; } else if ( token.type === 'invalidchar' || token.type === 'ws' || (token.type === 'punctuation' && token.string === '{') ) { // We're outside of a JSON key const constantCompletionHints = getCompletionHints(constantsToMatch, segment, TYPE_CONSTANT, MAX_CONSTANTS).map(hint => ({ ...hint, text: '"' + hint.text + '": ' })); highPriorityMatches = [...highPriorityMatches, ...constantCompletionHints]; } } else { // Otherwise match full segments const hints = getCompletionHints(constantsToMatch, nameSegmentFull, TYPE_CONSTANT, MAX_CONSTANTS); highPriorityMatches = [...highPriorityMatches, ...hints]; } } // Match tags if (allowMatchingTags) { const lowPriorityTagHints = getCompletionHints(tagsToMatch, nameSegment, TYPE_TAG, MAX_TAGS); lowPriorityMatches = [...lowPriorityMatches, ...lowPriorityTagHints]; const highPriorityTagHints = getCompletionHints(tagsToMatch, nameSegmentLong, TYPE_TAG, MAX_TAGS); highPriorityMatches = [...highPriorityMatches, ...highPriorityTagHints]; } const snippetHints = getCompletionHints(snippetsToMatch, nameSegment, TYPE_SNIPPET, MAX_SNIPPETS); highPriorityMatches = [...highPriorityMatches, ...snippetHints]; const matches = [...highPriorityMatches, ...lowPriorityMatches]; // Autocomplete from longest matched segment const segment = highPriorityMatches.length ? nameSegmentLong : nameSegment; const uniqueMatches = matches.reduce( (arr, v) => (arr.find(a => a.text === v.text) ? arr : [...arr, v]), [] as Hint[], // Default value ); return { list: uniqueMatches, from: CodeMirror.Pos(cur.line, cur.ch - segment.length), to: CodeMirror.Pos(cur.line, cur.ch), }; }
/** * Function to retrieve the list items * @param cm * @param options * @returns {Promise.<{list: Array, from, to}>} */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/autocomplete.ts#L235-L352
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
replaceHintMatch
async function replaceHintMatch(cm: CodeMirror.Editor, _self: any, data: any) { if (typeof data.text === 'function') { data.text = await data.text(); } const cur = cm.getCursor(); const from = CodeMirror.Pos(cur.line, cur.ch - data.segment.length); const to = CodeMirror.Pos(cur.line, cur.ch); const prevStart = CodeMirror.Pos(from.line, from.ch - 10); const prevChars = cm.getRange(prevStart, from); const nextEnd = CodeMirror.Pos(to.line, to.ch + 10); const nextChars = cm.getRange(to, nextEnd); let prefix = ''; let suffix = ''; if (data.type === TYPE_VARIABLE && !prevChars.match(/{{[^}]*$/)) { prefix = '{{ '; // If no closer before } else if (data.type === TYPE_VARIABLE && prevChars.match(/{{$/)) { prefix = ' '; // If no space after opener } else if (data.type === TYPE_TAG && prevChars.match(/{%$/)) { prefix = ' '; // If no space after opener } else if (data.type === TYPE_TAG && !prevChars.match(/{%[^%]*$/)) { prefix = '{% '; // If no closer before } if (data.type === TYPE_VARIABLE && !nextChars.match(/^\s*}}/)) { suffix = ' }}'; // If no closer after } else if (data.type === TYPE_VARIABLE && nextChars.match(/^}}/)) { suffix = ' '; // If no space before closer } else if (data.type === TYPE_TAG && nextChars.match(/^%}/)) { suffix = ' '; // If no space before closer } else if (data.type === TYPE_TAG && nextChars.match(/^\s*}/)) { // Edge case because "%" doesn't auto-close tags so sometimes you end // up in the scenario of {% foo} suffix = ' %'; } else if (data.type === TYPE_TAG && !nextChars.match(/^\s*%}/)) { suffix = ' %}'; // If no closer after } cm.replaceRange(`${prefix}${data.text}${suffix}`, from, to); }
/** * Replace the text in the EditorFromTextArea when a hint is selected. * This also makes sure there is whitespace surrounding it * @param cm * @param self * @param data */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/autocomplete.ts#L361-L401
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
replaceWithSurround
function replaceWithSurround(text: string, find: string, prefix: string, suffix: string) { const escapedString = escapeRegex(find); const re = new RegExp(escapedString, 'gi'); return text.replace(re, matched => prefix + matched + suffix); }
/** * Replace all occurrences of string */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/autocomplete.ts#L503-L507
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
renderHintMatch
function renderHintMatch(li: HTMLElement, _allHints: CodeMirror.Hints, hint: Hint) { // Bold the matched text const { displayText, segment, type, displayValue } = hint; const markedName = replaceWithSurround(displayText || '', segment, '<strong>', '</strong>'); const { char, title } = ICONS[type]; let safeValue = ''; if (isNotNullOrUndefined<string>(displayValue)) { const escaped = escapeHTML(displayValue); safeValue = ` <div class="value" title=${escaped}> ${escaped} </div> `; } li.className += ` fancy-hint type--${type}`; li.innerHTML = ` <label class="label" title="${title}">${char}</label> <div class="name">${markedName}</div> ${safeValue} `; }
/** * Render the autocomplete list entry */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/autocomplete.ts#L517-L539
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
beforeChangeCb
const beforeChangeCb = (_cm: any, change: any) => { if (change.origin === 'paste') { change.origin = '+dnd'; } };
// Modify paste events so we can merge into them
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/nunjucks-tags.ts#L185-L189
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
compare
const compare = < T extends GraphQLNamedType | GraphQLFieldWithParentName, U extends GraphQLNamedType | GraphQLFieldWithParentName >(a?: T, b?: U) => (!a && !b) || (a && b && a.name === b.name);
// @TODO Simplify this function since it's hard to follow along
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/graph-ql-explorer/graph-ql-explorer.tsx#L34-L37
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
isPromise
function isPromise(obj: unknown) { return ( !!obj && (typeof obj === 'object' || typeof obj === 'function') && // @ts-expect-error -- not updating because this came directly from the npm typeof obj.then === 'function' ); }
// Taken from https://github.com/then/is-promise
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/themed-button/async-button.tsx#L7-L14
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getMask
const getMask = () => MASK_CHARACTER.repeat(4 + (Math.random() * 7));
/** randomly get anywhere between 4 and 11 mask characters on each invocation */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/viewers/password-viewer.tsx#L14-L14
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
useTimeoutWhen
function useTimeoutWhen( callback_: () => void, timeoutDelayMs = 0, when = true ): void { const savedRefCallback = useRef<() => any>(); useEffect(() => { savedRefCallback.current = callback_; }); function callback() { savedRefCallback.current && savedRefCallback.current(); } useEffect(() => { if (when) { if (typeof window !== 'undefined') { const timeout = window.setTimeout(callback, timeoutDelayMs); return () => { window.clearTimeout(timeout); }; } else { console.warn('useTimeoutWhen: window is undefined.'); } } return; }, [timeoutDelayMs, when]); }
// https://github.com/imbhargav5/rooks/blob/main/src/hooks/useTimeoutWhen.ts
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/hooks/useTimeoutWhen.ts#L12-L41
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
flattenFoldersIntoList
const flattenFoldersIntoList = async (id: string): Promise<string[]> => { const parentIds: string[] = [id]; const folderIds = (await models.requestGroup.findByParentId(id)).map(r => r._id); if (folderIds.length) { await Promise.all(folderIds.map(async folderIds => parentIds.push(...(await flattenFoldersIntoList(folderIds))))); } return parentIds; };
// first recursion to get all the folders ids in order to use nedb search by an array
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/routes/workspace.tsx#L135-L142
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getCollectionTree
const getCollectionTree = async ({ parentId, level, parentIsCollapsed, ancestors, }: { parentId: string; level: number; parentIsCollapsed: boolean; ancestors: string[]; }): Promise<Child[]> => { const levelReqs = allRequests.filter(r => r.parentId === parentId); const childrenWithChildren: Child[] = await Promise.all(levelReqs .sort(sortFunction) .map(async (doc): Promise<Child> => { const isMatched = (filter: string): boolean => Boolean(fuzzyMatchAll( filter, [ doc.name, doc.description, ...(isRequestGroup(doc) ? [] : [doc.url]), ], { splitSpace: true, loose: true } )?.indexes); const shouldHide = Boolean(filter && !isMatched(filter)); const hidden = parentIsCollapsed || shouldHide; const pinned = !isRequestGroup(doc) && grpcAndRequestMetas.find(m => m.parentId === doc._id)?.pinned || false; const collapsed = filter ? false : parentIsCollapsed || (isRequestGroup(doc) && requestGroupMetas.find(m => m.parentId === doc._id)?.collapsed) || false; const docAncestors = [...ancestors, parentId]; return { doc, pinned, collapsed, hidden, level, ancestors: docAncestors, children: await getCollectionTree({ parentId: doc._id, level: level + 1, parentIsCollapsed: collapsed, ancestors: docAncestors, }), }; }), ); return childrenWithChildren; };
// second recursion to build the tree
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/routes/workspace.tsx#L167-L222
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
pairsToDataParameters
const pairsToDataParameters = (keyedPairs: PairsByName): Parameter[] => { let dataParameters: Parameter[] = []; for (const flagName of dataFlags) { const pairs = keyedPairs[flagName]; if (!pairs || pairs.length === 0) { continue; } switch (flagName) { case 'd': case 'data': case 'data-ascii': case 'data-binary': dataParameters = dataParameters.concat(pairs.flatMap(pair => pairToParameters(pair, true))); break; case 'data-raw': dataParameters = dataParameters.concat(pairs.flatMap(pair => pairToParameters(pair))); break; case 'data-urlencode': dataParameters = dataParameters.concat(pairs.flatMap(pair => pairToParameters(pair, true)) .map(parameter => { if (parameter.type === 'file') { return parameter; } return { ...parameter, value: encodeURIComponent(parameter.value ?? ''), }; })); break; default: throw new Error(`unhandled data flag ${flagName}`); } } return dataParameters; };
/** * Parses pairs supporting only flags dictated by {@link dataFlags} * * @param keyedPairs pairs with cURL flags as keys. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/curl.ts#L280-L319
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
pairToParameters
const pairToParameters = (pair: Pair, allowFiles = false): Parameter[] => { if (typeof pair === 'boolean') { return [{ name: '', value: pair.toString() }]; } return pair.split('&').map(pair => { if (pair.includes('@') && allowFiles) { const [name, fileName] = pair.split('@'); return { name, fileName, type: 'file' }; } const [name, value] = pair.split('='); if (!value || !pair.includes('=')) { return { name: '', value: pair }; } return { name, value }; }); };
/** * Converts pairs (that could include multiple via `&`) into {@link Parameter}s. This * method supports both `@filename` and `name@filename`. * * @param pair command line value * @param allowFiles whether to allow the `@` to support include files */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/curl.ts#L328-L346
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getServerUrl
const getServerUrl = (server: OpenAPIV3.ServerObject) => { const exampleServer = 'http://example.com/'; if (!(server && server.url)) { return urlParse(exampleServer); } const url = resolveVariables(server); return urlParse(url); };
/** * Gets a server to use as the default * Either the first server defined in the specification, or an example if none are specified * * @returns the resolved server URL */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L67-L76
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
resolveVariables
const resolveVariables = (server: OpenAPIV3.ServerObject) => { let resolvedUrl = server.url; const variables = server.variables || {}; let shouldContinue = true; do { // Regexp contain the global flag (g), meaning we must execute our regex on the original string. // https://stackoverflow.com/a/27753327 const [replace, name] = VARIABLE_SEARCH_VALUE.exec(server.url) || []; const variable = variables && variables[name]; const value = variable && variable.default; if (name && !value) { // We found a variable in the url (name) but we have no default to replace it with (value) throw new Error(`Server variable "${name}" missing default value`); } shouldContinue = !!name; resolvedUrl = replace ? resolvedUrl.replace(replace, value) : resolvedUrl; } while (shouldContinue); return resolvedUrl; };
/** * Resolve default variables for a server url * * @returns the resolved url */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L83-L105
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseDocument
const parseDocument = (rawData: string): OpenAPIV3.Document | null => { try { return (unthrowableParseJson(rawData) || YAML.parse(rawData)) as OpenAPIV3.Document; } catch (err) { return null; } };
/** * Parse string data into openapi 3 object (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#oasObject) */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L110-L117
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
isSpecExtension
const isSpecExtension = (property: string): property is SpecExtension => { return property.indexOf('x-') === 0; };
/** * Checks if the given property name is an open-api extension * @param property The property name */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L124-L126
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseEnvs
const parseEnvs = (baseEnv: ImportRequest, document?: OpenAPIV3.Document | null) => { if (!document) { return []; } let servers: OpenAPIV3.ServerObject[] | undefined; if (!document.servers) { servers = [{ url: 'http://example.com/' }]; } else { servers = document.servers; } const securityVariables = getSecurityEnvVariables( document.components?.securitySchemes as unknown as OpenAPIV3.SecuritySchemeObject, ); return servers .map(server => { const currentServerUrl = getServerUrl(server); const protocol = currentServerUrl.protocol || ''; // Base path is pulled out of the URL, and the trailing slash is removed const basePath = (currentServerUrl.pathname || '').replace(/\/$/, ''); const hash = crypto .createHash('sha1') .update(server.url) .digest('hex') .slice(0, 8); const openapiEnv: ImportRequest = { _type: 'environment', _id: `env___BASE_ENVIRONMENT_ID___sub__${hash}`, parentId: baseEnv._id, name: `OpenAPI env ${currentServerUrl.host}`, data: { // note: `URL.protocol` returns with trailing `:` (i.e. "https:") scheme: protocol.replace(/:$/, '') || ['http'], base_path: basePath, host: currentServerUrl.host || '', ...securityVariables, }, }; return openapiEnv; }) || []; };
/** * Create env definitions based on openapi document. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L131-L177
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseEndpoints
const parseEndpoints = (document?: OpenAPIV3.Document | null) => { if (!document) { return []; } const rootSecurity = document.security; const securitySchemes = document.components?.securitySchemes as OpenAPIV3.SecuritySchemeObject | undefined; const defaultParent = WORKSPACE_ID; const endpointsSchemas: ({ path: string; method: string; tags?: string[]; } & OpenAPIV3.SchemaObject)[] = Object.keys(document.paths) .map(path => { const schemasPerMethod = document.paths[path]; if (!schemasPerMethod) { return []; } const methods = Object.entries(schemasPerMethod) // Only keep entries that are plain objects and not spec extensions .filter(([key, value]) => isPlainObject(value) && !isSpecExtension(key)); return methods.map(([method]) => ({ ...((schemasPerMethod as Record<string, OpenAPIV3.SchemaObject>)[method]), path, method, })); }) .flat(); const folders = document.tags?.map(importFolderItem(defaultParent)) || []; const folderLookup = folders.reduce((accumulator, folder) => ({ ...accumulator, ...(folder.name ? { [folder.name]: folder._id } : {}), }), {} as Record<OpenAPIV3.TagObject['name'], string | undefined>); const requests: ImportRequest[] = []; endpointsSchemas.forEach(endpointSchema => { let { tags } = endpointSchema; if (!tags || tags.length === 0) { tags = ['']; } tags.forEach(tag => { const parentId = folderLookup[tag] || defaultParent; const resolvedSecurity = (endpointSchema as unknown as OpenAPIV3.Document).security || rootSecurity; requests.push( importRequest( endpointSchema, parentId, resolvedSecurity, securitySchemes, ), ); }); }); return [ ...folders, ...requests, ]; };
/** * Create request definitions based on openapi document. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L182-L247
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
importFolderItem
const importFolderItem = (parentId: string) => ( item: OpenAPIV3.SchemaObject, ): ImportRequest => { const hash = crypto .createHash('sha1') // @ts-expect-error -- this is not present on the official types, yet was here in the source code .update(item.name) .digest('hex') .slice(0, 8); return { parentId, _id: `fld___WORKSPACE_ID__${hash}`, _type: 'request_group', // @ts-expect-error -- this is not present on the official types, yet was here in the source code name: item.name || 'Folder {requestGroupCount}', description: item.description || '', }; };
/** * Return Insomnium folder / request group */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L252-L269
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
pathWithParamsAsVariables
const pathWithParamsAsVariables = (path?: string) => path?.replace(VARIABLE_SEARCH_VALUE, '{{ _.$1 }}') ?? '';
/** * Return path with parameters replaced by insomnia variables * * I.e. "/foo/:bar" => "/foo/{{ bar }}" */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L276-L277
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
importRequest
const importRequest = ( endpointSchema: OpenAPIV3.SchemaObject & { summary?: string; path?: string; method?: string }, parentId: string, security?: OpenAPIV3.SecurityRequirementObject[], securitySchemes?: OpenAPIV3.SecuritySchemeObject, ): ImportRequest => { const name = endpointSchema.summary || endpointSchema.path; const id = generateUniqueRequestId(endpointSchema as OpenAPIV3.OperationObject); const body = prepareBody(endpointSchema); const paramHeaders = prepareHeaders(endpointSchema, body); const { authentication, headers: securityHeaders, parameters: securityParams, } = parseSecurity(security, securitySchemes); return { _type: 'request', _id: id, parentId: parentId, name, method: endpointSchema.method?.toUpperCase(), url: `{{ _.base_url }}${pathWithParamsAsVariables(endpointSchema.path)}`, body: body, headers: [...paramHeaders, ...securityHeaders], authentication: authentication as Authentication, parameters: [...prepareQueryParams(endpointSchema), ...securityParams], }; };
/** * Return Insomnium request */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L282-L309
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareQueryParams
const prepareQueryParams = (endpointSchema: OpenAPIV3.PathItemObject) => { return convertParameters( endpointSchema.parameters?.filter(parameter => ( (parameter as OpenAPIV3.ParameterObject).in === 'query' )) as OpenAPIV3.ParameterObject[]); };
/** * Imports insomnia definitions of query parameters. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L314-L319
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareHeaders
const prepareHeaders = (endpointSchema: OpenAPIV3.PathItemObject, body: any) => { let paramHeaders = convertParameters( endpointSchema.parameters?.filter(parameter => ( (parameter as OpenAPIV3.ParameterObject).in === 'header' )) as OpenAPIV3.ParameterObject[]); const noContentTypeHeader = !paramHeaders?.find( header => header.name === 'Content-Type', ); if (body && body.mimeType && noContentTypeHeader) { paramHeaders = [ { name: 'Content-Type', disabled: false, value: body.mimeType, }, ...paramHeaders, ]; } return paramHeaders; };
/** * Imports insomnia definitions of header parameters. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L324-L345
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseSecurity
const parseSecurity = ( security?: OpenAPIV3.SecurityRequirementObject[], securitySchemes?: OpenAPIV3.SecuritySchemeObject, ) => { if (!security || !securitySchemes) { return { authentication: {}, headers: [], parameters: [], }; } const supportedSchemes = security .flatMap(securityPolicy => { return Object.keys(securityPolicy).map((securityRequirement: string | number) => { return { // @ts-expect-error the base types do not include an index but from what I can tell, they should schemeDetails: securitySchemes[securityRequirement], securityScopes: securityPolicy[securityRequirement], }; }); }) .filter(({ schemeDetails }) => ( schemeDetails && SUPPORTED_SECURITY_TYPES.includes(schemeDetails.type) )); const apiKeySchemes = supportedSchemes.filter(scheme => ( scheme.schemeDetails.type === SECURITY_TYPE.API_KEY )); const apiKeyHeaders = apiKeySchemes .filter(scheme => scheme.schemeDetails.in === 'header') .map(scheme => { const variableName = camelCase(scheme.schemeDetails.name); return { name: scheme.schemeDetails.name, disabled: false, value: `{{ _.${variableName} }}`, }; }); const apiKeyCookies = apiKeySchemes .filter(scheme => scheme.schemeDetails.in === 'cookie') .map(scheme => { const variableName = camelCase(scheme.schemeDetails.name); return `${scheme.schemeDetails.name}={{ _.${variableName} }}`; }); const apiKeyCookieHeader = { name: 'Cookie', disabled: false, value: apiKeyCookies.join('; '), }; const apiKeyParams = apiKeySchemes .filter(scheme => scheme.schemeDetails.in === 'query') .map(scheme => { const variableName = camelCase(scheme.schemeDetails.name); return { name: scheme.schemeDetails.name, disabled: false, value: `{{ _.${variableName} }}`, }; }); const apiKeySecuritySchemas = apiKeyHeaders.length + apiKeyCookies.length + apiKeyParams.length; if (apiKeyCookies.length > 0) { apiKeyHeaders.push(apiKeyCookieHeader); } const authentication = (() => { const authScheme = supportedSchemes.find( scheme => SUPPORTED_SECURITY_TYPES.includes(scheme.schemeDetails.type) && (scheme.schemeDetails.type === SECURITY_TYPE.OAUTH || (apiKeySecuritySchemas === 1 && scheme.schemeDetails.type === SECURITY_TYPE.API_KEY) || SUPPORTED_HTTP_AUTH_SCHEMES.includes(scheme.schemeDetails.scheme)), ); if (!authScheme) { return {}; } switch (authScheme.schemeDetails.type) { case SECURITY_TYPE.HTTP: return parseHttpAuth( (authScheme.schemeDetails as OpenAPIV3.HttpSecurityScheme).scheme, ); case SECURITY_TYPE.OAUTH: return parseOAuth2(authScheme.schemeDetails as OpenAPIV3.OAuth2SecurityScheme, authScheme.securityScopes); case SECURITY_TYPE.API_KEY: return parseApiKeyAuth(authScheme.schemeDetails as OpenAPIV3.ApiKeySecurityScheme); default: return {}; } })(); const isApiKeyAuth = authentication?.type?.toLowerCase() === SECURITY_TYPE.API_KEY.toLowerCase(); return { authentication: authentication, headers: isApiKeyAuth ? [] : apiKeyHeaders, parameters: isApiKeyAuth ? [] : apiKeyParams, }; };
/** * Parse OpenAPI 3 securitySchemes into insomnia definitions of authentication, headers and parameters * @returns headers or basic|bearer http authentication details */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L351-L453
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getSecurityEnvVariables
const getSecurityEnvVariables = (securitySchemeObject?: OpenAPIV3.SecuritySchemeObject) => { if (!securitySchemeObject) { return {}; } const securitySchemes = Object.values(securitySchemeObject); const apiKeyVariableNames = securitySchemes .filter(scheme => scheme.type === SECURITY_TYPE.API_KEY) .map(scheme => camelCase(scheme.name)); const variables: Record<string, string> = {}; Array.from(new Set(apiKeyVariableNames)).forEach(name => { variables[name] = name; }); const hasHttpBasicScheme = securitySchemes.some(scheme => ( scheme.type === SECURITY_TYPE.HTTP && scheme.scheme === 'basic' )); if (hasHttpBasicScheme) { variables.httpUsername = 'username'; variables.httpPassword = 'password'; } const hasHttpBearerScheme = securitySchemes.some(scheme => ( scheme.type === SECURITY_TYPE.HTTP && scheme.scheme === 'bearer' )); if (hasHttpBearerScheme) { variables.bearerToken = 'bearerToken'; } const oauth2Variables = securitySchemes.reduce((accumulator, scheme) => { if (scheme.type === SECURITY_TYPE.OAUTH) { accumulator.oauth2ClientId = 'clientId'; const flows = scheme.flows || {}; if ( flows.authorizationCode || flows.implicit ) { accumulator.oauth2RedirectUrl = 'http://localhost/'; } if ( flows.authorizationCode || flows.clientCredentials || flows.password ) { accumulator.oauth2ClientSecret = 'clientSecret'; } if (flows.password) { accumulator.oauth2Username = 'username'; accumulator.oauth2Password = 'password'; } } return accumulator; }, {}); return { ...variables, ...oauth2Variables, }; };
/** * Get Insomnium environment variables for OpenAPI securitySchemes * * @returns Insomnium environment variables containing security information */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L460-L522
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareBody
const prepareBody = (endpointSchema: OpenAPIV3.OperationObject): ImportRequest['body'] => { const { content } = (endpointSchema.requestBody || { content: {} }) as OpenAPIV3.RequestBodyObject; const mimeTypes = Object.keys(content); const supportedMimeType = mimeTypes.find(reqMimeType => { return SUPPORTED_MIME_TYPES.some(supportedMimeType => { return reqMimeType.includes(supportedMimeType); }); }); if (supportedMimeType && supportedMimeType.includes(MIMETYPE_JSON)) { const bodyParameter = content[supportedMimeType]; if (bodyParameter == null) { return { mimeType: MIMETYPE_JSON, }; } const example = generateParameterExample(bodyParameter.schema as OpenAPIV3.SchemaObject); const text = JSON.stringify(example, null, 2); return { mimeType: MIMETYPE_JSON, text, }; } if ( mimeTypes && mimeTypes.length && mimeTypes[0] !== MIMETYPE_LITERALLY_ANYTHING ) { return { mimeType: mimeTypes[0] || undefined, }; } else { return {}; } };
/** * Imports insomnia request body definitions, including data mock (if available) * * If multiple types are available, the one for which an example can be generated will be selected first (i.e. application/json) */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L529-L567
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
convertParameters
const convertParameters = (parameters: OpenAPIV3.ParameterObject[] = []) => { return parameters.map(parameter => { const { required, name, schema } = parameter; return { name, disabled: required !== true, value: `${generateParameterExample(schema as OpenAPIV3.SchemaObject)}`, }; }); };
/** * Converts openapi schema of parameters into insomnia one. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L572-L581
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
generateParameterExample
const generateParameterExample = (schema: OpenAPIV3.SchemaObject | string) => { const typeExamples = { string: () => 'string', string_email: () => 'user@example.com', 'string_date-time': () => new Date().toISOString(), string_byte: () => 'ZXhhbXBsZQ==', number: () => 0, number_float: () => 0.0, number_double: () => 0.0, integer: () => 0, boolean: () => true, object: (schema: OpenAPIV3.SchemaObject) => { const example: OpenAPIV3.SchemaObject['properties'] = {}; const { properties } = schema; if (properties) { for (const propertyName of Object.keys(properties)) { example[propertyName] = generateParameterExample( properties[propertyName] as OpenAPIV3.SchemaObject, ); } } return example; }, // @ts-expect-error -- ran out of time during TypeScript conversion to handle this particular recursion array: (schema: OpenAPIV2.ItemsObject) => { // @ts-expect-error -- ran out of time during TypeScript conversion to handle this particular recursion const value = generateParameterExample(schema.items); if (schema.collectionFormat === 'csv') { return value; } else { return [value]; } }, }; if (typeof schema === 'string') { // @ts-expect-error -- ran out of time during TypeScript conversion to handle this particular recursion return typeExamples[schema]; } if (schema instanceof Object) { const { type, format, example, readOnly, default: defaultValue } = schema; if (readOnly) { return undefined; } if (example) { return example; } if (defaultValue) { return defaultValue; } // @ts-expect-error -- ran out of time during TypeScript conversion to handle this particular recursion const factory = typeExamples[`${type}_${format}`] || typeExamples[type]; if (!factory) { return null; } return factory(schema); } };
/** * Generate example value of parameter based on it's schema. * Returns example / default value of the parameter, if any of those are defined. If not, returns value based on parameter type. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L588-L655
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
generateUniqueRequestId
const generateUniqueRequestId = ( endpointSchema: OpenAPIV3.OperationObject<{ method?: string; path?: string }>, ) => { // `operationId` is already unique to the workspace, so we can just use that, combined with the workspace id to get something globally unique const uniqueKey = endpointSchema.operationId || `[${endpointSchema.method}]${endpointSchema.path}`; const hash = crypto .createHash('sha1') .update(uniqueKey) .digest('hex') .slice(0, 8); // Suffix the ID with a counter in case we try creating two with the same hash if (requestCounts.hasOwnProperty(hash)) { requestCounts[hash] += 1; } else { requestCounts[hash] = 0; } return `req_${WORKSPACE_ID}${hash}${requestCounts[hash] || ''}`; };
/** * Generates a unique and deterministic request ID based on the endpoint schema */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L660-L680
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
ImportPostman.importDigestAuthenticationFromHeader
importАwsv4AuthenticationFromHeader = (authHeader: string, headers: Header[]) => { if (!authHeader) { return { authentication: {}, headers, }; } const isAMZSecurityTokenHeader = ({ key }: Header) => key === 'X-Amz-Security-Token'; const sessionToken = headers?.find(isAMZSecurityTokenHeader)?.value; const credentials = RegExp(/(?<=Credential=).*/).exec(authHeader)?.[0].split('/'); return { authentication: { type: 'iam', disabled: false, accessKeyId: credentials?.[0], region: credentials?.[2], secretAccessKey: '', service: credentials?.[3], ...(sessionToken ? { sessionToken } : {}), }, headers: headers.filter(h => !isAMZSecurityTokenHeader(h)), }; }
// example: Digest username="Username", realm="Realm", nonce="Nonce", uri="//api/v1/report?start_date_min=2019-01-01T00%3A00%3A00%2B00%3A00&start_date_max=2019-01-01T23%3A59%3A59%2B00%3A00&projects[]=%2Fprojects%2F1&include_child_projects=1&search_query=meeting&columns[]=project&include_project_data=1&sort[]=-duration", algorithm="MD5", response="f3f762321e158aefe103529eda4ddb7c", opaque="Opaque"
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/postman.ts
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
importFolderItem
const importFolderItem = (parentId: string) => ( item: OpenAPIV2.TagObject, ): ImportRequest => { const hash = crypto .createHash('sha1') .update(item.name) .digest('hex') .slice(0, 8); return { parentId, _id: `fld___WORKSPACE_ID__${hash}`, _type: 'request_group', name: item.name || 'Folder {requestGroupCount}', description: item.description || '', }; };
/* eslint-disable camelcase -- this file uses camel case too often */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L29-L44
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseDocument
const parseDocument = (rawData: string) => { try { return unthrowableParseJson(rawData) || YAML.parse(rawData); } catch (err) { return null; } };
/** * Parse string data into swagger 2.0 object (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object) */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L49-L55
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseEndpoints
const parseEndpoints = (document: OpenAPIV2.Document) => { const defaultParent = WORKSPACE_ID; const globalMimeTypes = document.consumes ?? []; const endpointsSchemas: OpenAPIV2.OperationObject[] = Object.keys( document.paths, ) .map((path: keyof OpenAPIV2.PathsObject) => { const schemasPerMethod: OpenAPIV2.PathItemObject = document.paths[path]; const methods = Object.keys( schemasPerMethod, ) as (keyof OpenAPIV2.PathItemObject)[]; return methods .filter(method => method !== 'parameters' && method !== '$ref') .map(method => ({ ...(schemasPerMethod[method] as OpenAPIV2.OperationObject), path, method, })); }) .flat(); const tags = document.tags || []; const implicitTags = endpointsSchemas .map(endpointSchema => endpointSchema.tags) .flat() .reduce((distinct, value) => { // remove duplicates if (value !== undefined && !distinct.includes(value)) { distinct.push(value); } return distinct; }, [] as string[]) .filter(tag => !tags.map(tag => tag.name).includes(tag)) .map(name => ({ name, description: '' })); const folders = [...tags, ...implicitTags].map( importFolderItem(defaultParent), ); const folderLookup = folders.reduce( (accumulator, { _id, name }) => ({ ...accumulator, ...(name === undefined ? {} : { [name]: _id }), }), {} as { [name: string]: string | undefined }, ); const requests: ImportRequest[] = []; endpointsSchemas.map(endpointSchema => { let { tags } = endpointSchema; if (!tags || tags.length === 0) { tags = ['']; } tags.forEach((tag, index) => { const requestId = endpointSchema.operationId ? `${endpointSchema.operationId}${index > 0 ? index : ''}` : `__REQUEST_${requestCount++}__`; const parentId = folderLookup[tag] || defaultParent; requests.push( importRequest( document, endpointSchema, globalMimeTypes, requestId, parentId, ), ); }); }); return [...folders, ...requests]; };
/** * Create request definitions based on swagger document. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L60-L133
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
setupAuthentication
const setupAuthentication = ( securityDefinitions: OpenAPIV2.SecurityDefinitionsObject | undefined, endpointSchema: OpenAPIV2.OperationObject | undefined, request: ImportRequest, ) => { if (!securityDefinitions) { return request; } if (!endpointSchema?.security || endpointSchema.security.length === 0) { return request; } const usedDefinitions = endpointSchema.security.reduce( (collect, requirement) => [ ...collect, ...(Object.keys(requirement) as string[]), ], [] as string[], ); const scopes = endpointSchema.security.reduce((accumulator, security) => { for (const defname of Object.keys(security)) { if (security[defname].length === 0) { continue; } return accumulator.concat(security[defname]); } return accumulator; }, [] as string[]); for (const usedDefinition of usedDefinitions) { const securityScheme = securityDefinitions[usedDefinition]; if (securityScheme.type === 'basic') { request.authentication = { type: 'basic', disabled: false, password: '{{ _.password }}', username: '{{ _.username }}', }; } if (securityScheme.type === 'apiKey') { if (securityScheme.in === 'header') { request.headers?.push({ name: securityScheme.name, disabled: false, value: '{{ _.api_key }}', }); } if (securityScheme.in === 'query') { request.parameters?.push({ name: securityScheme.name, disabled: false, value: '{{ _.api_key }}', }); } } if (securityScheme.type === 'oauth2') { if (securityScheme.flow === 'implicit') { request.authentication = { type: 'oauth2', grantType: 'authorization_code', disabled: false, authorizationUrl: securityScheme.authorizationUrl, clientId: '{{ _.client_id }}', scope: scopes.join(' '), }; } if (securityScheme.flow === 'password') { request.authentication = { type: 'oauth2', grantType: 'password', disabled: false, accessTokenUrl: securityScheme.tokenUrl, username: '{{ _.username }}', password: '{{ _.password }}', clientId: '{{ _.client_id }}', clientSecret: '{{ _.client_secret }}', scope: scopes.join(' '), }; } if (securityScheme.flow === 'application') { request.authentication = { type: 'oauth2', grantType: 'client_credentials', disabled: false, accessTokenUrl: securityScheme.tokenUrl, clientId: '{{ _.client_id }}', clientSecret: '{{ _.client_secret }}', scope: scopes.join(' '), }; } if (securityScheme.flow === 'accessCode') { request.authentication = { type: 'oauth2', grantType: 'authorization_code', disabled: false, accessTokenUrl: securityScheme.tokenUrl, authorizationUrl: securityScheme.authorizationUrl, clientId: '{{ _.client_id }}', clientSecret: '{{ _.client_secret }}', scope: scopes.join(' '), }; } } } return request; };
/** * Populate Insomnium request with authentication */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L186-L302
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
pathWithParamsAsVariables
const pathWithParamsAsVariables = (path?: string) => { return path?.replace(/{([^}]+)}/g, '{{ _.$1 }}'); };
/** * Return path with parameters replaced by insomnia variables * * I.e. "/foo/:bar" => "/foo/{{ bar }}" */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L309-L311
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareQueryParams
const prepareQueryParams = (endpointSchema: OpenAPIV2.OperationObject) => { return ( convertParameters( ((endpointSchema.parameters as unknown) as OpenAPIV2.Parameter[])?.filter( parameter => parameter.in === 'query', ), ) || [] ); };
/** * Imports insomnia definitions of query parameters. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L316-L324
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareHeaders
const prepareHeaders = ( endpointSchema: OpenAPIV2.OperationObject, ): Header[] => { return ( (convertParameters( ((endpointSchema.parameters as unknown) as OpenAPIV2.Parameter[])?.filter( parameter => parameter.in === 'header', ), ) as Header[]) || [] ); };
/** * Imports insomnia definitions of header parameters. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L329-L339
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareBody
const prepareBody = ( document: OpenAPIV2.Document, endpointSchema: OpenAPIV2.OperationObject, globalMimeTypes: OpenAPIV2.MimeTypes, ) => { const mimeTypes = endpointSchema.consumes || globalMimeTypes || []; const supportedMimeType = mimeTypes.find(reqMimeType => { return SUPPORTED_MIME_TYPES.some(supportedMimeType => { return reqMimeType.includes(supportedMimeType); }); }); if (supportedMimeType && supportedMimeType.includes(MIMETYPE_JSON)) { const parameters = endpointSchema.parameters || []; const bodyParameter = parameters.find( parameter => (parameter as OpenAPIV2.Parameter).in === 'body', ); if (!bodyParameter) { return {}; } const type = (bodyParameter as OpenAPIV2.ParameterObject).type || 'object'; const example = generateParameterExample(type); let text; if (type === 'object') { const { schema } = bodyParameter as OpenAPIV2.ParameterObject; if (schema.$ref) { const definition = resolve$ref(document, schema.$ref); text = JSON.stringify(example(definition), null, 2); } else { text = JSON.stringify(example(schema), null, 2); } } else { text = JSON.stringify(example, null, 2); } return { mimeType: supportedMimeType, text, }; } if (supportedMimeType && (supportedMimeType.includes(MIMETYPE_URLENCODED) || supportedMimeType.includes(MIMETYPE_MULTIPART))) { const parameters = endpointSchema.parameters || []; const formDataParameters = ((parameters as unknown) as OpenAPIV2.Parameter[]).filter( parameter => parameter.in === 'formData', ); if (formDataParameters.length === 0) { return {}; } return { mimeType: supportedMimeType, params: convertParameters(formDataParameters), }; } if (mimeTypes && mimeTypes.length) { return { mimeType: mimeTypes[0] || undefined, }; } else { return {}; } };
/** * Imports insomnia request body definitions, including data mock (if available) * * If multiple types are available, the one for which an example can be generated will be selected first (i.e. application/json) */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L354-L422
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
generateParameterExample
const generateParameterExample = ( parameter: OpenAPIV2.Parameter | TypeExample, ancestors: OpenAPIV2.Parameter[] = [], ) => { const typeExamples: { [kind in TypeExample]: ( parameter: OpenAPIV2.Parameter ) => null | string | boolean | number | Record<string, unknown>; } = { string: () => 'string', string_email: () => 'user@example.com', 'string_date-time': () => new Date().toISOString(), string_byte: () => 'ZXhhbXBsZQ==', number: () => 0, number_float: () => 0.0, number_double: () => 0.0, integer: () => 0, boolean: () => true, object: (parameter: OpenAPIV2.Parameter) => { if (ancestors.indexOf(parameter) !== -1) { return {}; } const example = {}; const { properties } = parameter; if (properties) { ancestors.push(parameter); Object.keys(properties).forEach(propertyName => { // @ts-expect-error there's no way, so far as I'm aware, for TypeScript to know what's actually going on here. example[propertyName] = generateParameterExample( properties[propertyName], ancestors, ); }); ancestors.pop(); } return example; }, array: ({ items, collectionFormat }: OpenAPIV2.Parameter) => { const value = generateParameterExample(items, ancestors); if (collectionFormat === 'csv') { return value; } else { return [value]; } }, }; if (typeof parameter === 'string') { return typeExamples[parameter]; } if (typeof parameter === 'object') { const { type, format, example, default: defaultValue } = parameter; if (example) { return example; } if (defaultValue) { return defaultValue; } const factory = typeExamples[`${type}_${format}` as TypeExample] || typeExamples[type as TypeExample]; if (!factory) { return null; } return factory(parameter); } };
/** * Generate example value of parameter based on it's schema. * Returns example / default value of the parameter, if any of those are defined. If not, returns value based on parameter type. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L441-L517
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
convertParameters
const convertParameters = (parameters?: OpenAPIV2.Parameter[]) => { return parameters?.map(parameter => { const { required, name, type } = parameter; if (type === 'file') { return { name, disabled: required !== true, type: 'file', }; } return { name, disabled: required !== true, value: `${generateParameterExample(parameter) as string}`, }; }); };
/** * Converts swagger schema of parameters into insomnia one. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L522-L540
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
convertUnicode
const convertUnicode = (originalStr: string) => { let m; let c; let cStr; let lastI = 0; // Matches \u#### but not \\u#### const unicodeRegex = /\\u[0-9a-fA-F]{4}/g; let convertedStr = ''; while ((m = unicodeRegex.exec(originalStr))) { // Don't convert if the backslash itself is escaped if (originalStr[m.index - 1] === '\\') { continue; } try { cStr = m[0].slice(2); // Trim off start c = String.fromCharCode(parseInt(cStr, 16)); if (c === '"') { // Escape it if it's double quotes c = `\\${c}`; } // + 1 to account for first matched (non-backslash) character convertedStr += originalStr.slice(lastI, m.index) + c; lastI = m.index + m[0].length; } catch (err) { // Some reason we couldn't convert a char. Should never actually happen console.warn('Failed to convert unicode char', m[0], err); } } // Finally, add the rest of the string to the end. convertedStr += originalStr.slice(lastI, originalStr.length); return convertedStr; };
/** * Convert escaped unicode characters to real characters. Any JSON parser will do this by * default. This is really fast too. Around 25ms for ~2MB of data with LOTS of unicode. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/prettify/json.ts#L173-L210
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
framework
github_2023
observablehq
typescript
addFile
const addFile = (path: string, f: string) => files.add(resolvePath(path, f));
// e.g., "/style.css"
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/build.ts#L69-L69
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
addToManifest
const addToManifest = (type: string, file: string, {title, path}: {title?: string | null; path: string}) => { buildManifest[type].push({ path: config.normalizePath(file), source: join("/", path), // TODO have route return path with leading slash? ...(title != null && {title}) }); };
// file is the serving path relative to the base (e.g., /foo)
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/build.ts#L89-L95
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
resolveLocalImport
const resolveLocalImport = async (path: string): Promise<string> => { const hash = (await loaders.getLocalModuleHash(path)).slice(0, 8); return applyHash(join("/_import", path), hash); };
// Copy over imported local modules, overriding import resolution so that
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/build.ts#L290-L293
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
RateLimiter.wait
async wait() { const nextTick = this._nextTick; this._nextTick = nextTick.then(() => new Promise((res) => setTimeout(res, 1000 / this.ratePerSecond))); await nextTick; }
/** Wait long enough to avoid going over the rate limit. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/concurrency.ts#L49-L53
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
resolveConfig
function resolveConfig(configPath: string, root = "."): string { return op.join(cwd(), root, configPath); }
/** * Returns the absolute path to the specified config file, which is specified as a * path relative to the given root (if any). If you want to import this, you should * pass the result to pathToFileURL. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/config.ts#L183-L185
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
importConfig
async function importConfig(path: string): Promise<ConfigSpec> { const {mtimeMs} = await stat(path); return (await import(`${pathToFileURL(path).href}?${mtimeMs}`)).default; }
// By using the modification time of the config, we ensure that we pick up any
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/config.ts#L189-L192
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
normalizePagePath
function normalizePagePath(pathname: string): string { ({pathname} = parseRelativeUrl(pathname)); // ignore query & anchor pathname = normalizePath(pathname); if (pathname.endsWith("/")) pathname = join(pathname, "index"); else pathname = pathname.replace(/\.html$/, ""); return pathname; }
// If this path ends with a slash, then add an implicit /index to the
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/config.ts#L290-L296
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.checkDeployCreated
private async checkDeployCreated(deployId: string) { try { const deployInfo = await this.apiClient.getDeploy(deployId); if (deployInfo.status !== "created") { throw new CliError(`Deploy ${deployId} has an unexpected status: ${deployInfo.status}`); } return deployInfo; } catch (error) { if (isHttpError(error)) { throw new CliError(`Deploy ${deployId} not found.`, { cause: error }); } throw error; } }
// Make sure deploy exists and has an expected status.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L205-L220
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.getUpdatedDeployConfig
private async getUpdatedDeployConfig() { const deployConfig = await this.effects.getDeployConfig( this.deployOptions.config.root, this.deployOptions.deployConfigPath, this.effects ); if (deployConfig.workspaceLogin && !deployConfig.workspaceLogin.match(/^@?[a-z0-9-]+$/)) { throw new CliError( `Found invalid workspace login in ${join(this.deployOptions.config.root, ".observablehq", "deploy.json")}: ${ deployConfig.workspaceLogin }.` ); } if (deployConfig.projectSlug && !deployConfig.projectSlug.match(/^[a-z0-9-]+$/)) { throw new CliError( `Found invalid \`projectSlug\` in ${join(this.deployOptions.config.root, ".observablehq", "deploy.json")}: ${ deployConfig.projectSlug }.` ); } if (deployConfig.projectId && (!deployConfig.projectSlug || !deployConfig.workspaceLogin)) { const spinner = this.effects.clack.spinner(); this.effects.clack.log.warn("The `projectSlug` or `workspaceLogin` is missing from your deploy.json."); spinner.start(`Searching for app ${deployConfig.projectId}`); let found = false; for (const workspace of this.currentUser.workspaces) { const projects = await this.apiClient.getWorkspaceProjects(workspace.login); const project = projects.find((p) => p.id === deployConfig.projectId); if (project) { deployConfig.projectSlug = project.slug; deployConfig.workspaceLogin = workspace.login; await this.effects.setDeployConfig( this.deployOptions.config.root, this.deployOptions.deployConfigPath, deployConfig, this.effects ); found = true; break; } } if (found) { spinner.stop(`App ${deployConfig.projectSlug} found in workspace @${deployConfig.workspaceLogin}.`); } else { spinner.stop(`App ${deployConfig.projectId} not found. Ignoring…`); } } return deployConfig; }
// Get the deploy config, updating if necessary.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L223-L274
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.getDeployTarget
private async getDeployTarget(deployConfig: DeployConfig): Promise<DeployTargetInfo> { let deployTarget: DeployTargetInfo; if (deployConfig.workspaceLogin && deployConfig.projectSlug) { try { const project = await this.apiClient.getProject({ workspaceLogin: deployConfig.workspaceLogin, projectSlug: deployConfig.projectSlug }); deployTarget = {create: false, workspace: project.owner, project}; } catch (error) { if (!isHttpError(error) || error.statusCode !== 404) { throw error; } } } deployTarget ??= await promptDeployTarget( this.effects, this.deployOptions.config, this.apiClient, this.currentUser ); if (!deployTarget.create) { // Check last deployed state. If it's not the same project, ask the user if // they want to continue anyways. In non-interactive mode just cancel. const targetDescription = `${deployTarget.project.title} (${deployTarget.project.slug}) in the @${deployTarget.workspace.login} workspace`; if (deployConfig.projectId && deployConfig.projectId !== deployTarget.project.id) { this.effects.clack.log.warn( wrapAnsi( `The \`projectId\` in your deploy.json does not match. Continuing will overwrite ${bold( targetDescription )}.`, this.effects.outputColumns ) ); if (this.effects.isTty) { const choice = await this.effects.clack.confirm({ message: "Do you want to continue deploying?", active: "Yes, overwrite", inactive: "No, cancel" }); if (!choice) { this.effects.clack.outro(yellow("Deploy canceled.")); } if (this.effects.clack.isCancel(choice) || !choice) { throw new CliError("User canceled deploy", {print: false, exitCode: 0}); } } else { throw new CliError("Cancelling deploy due to misconfiguration."); } } else if (deployConfig.projectId) { this.effects.clack.log.info(wrapAnsi(`Deploying to ${bold(targetDescription)}.`, this.effects.outputColumns)); } else { this.effects.clack.log.warn( wrapAnsi( `The \`projectId\` in your deploy.json is missing. Continuing will overwrite ${bold(targetDescription)}.`, this.effects.outputColumns ) ); if (this.effects.isTty) { const choice = await this.effects.clack.confirm({ message: "Do you want to continue deploying?", active: "Yes, overwrite", inactive: "No, cancel" }); if (!choice) { this.effects.clack.outro(yellow("Deploy canceled.")); } if (this.effects.clack.isCancel(choice) || !choice) { throw new CliError("User canceled deploy", {print: false, exitCode: 0}); } } else { throw new CliError("Running non-interactively, cancelling due to conflict."); } } } if (deployTarget.create) { try { const project = await this.apiClient.postProject({ slug: deployTarget.projectSlug, title: deployTarget.title, workspaceId: deployTarget.workspace.id, accessLevel: deployTarget.accessLevel }); deployTarget = {create: false, workspace: deployTarget.workspace, project}; } catch (error) { if (isApiError(error) && error.details.errors.some((e) => e.code === "TOO_MANY_PROJECTS")) { this.effects.clack.log.error( wrapAnsi( `The Starter tier can only deploy one app. Upgrade to unlimited apps at ${link( `https://observablehq.com/team/@${deployTarget.workspace.login}/settings` )}`, this.effects.outputColumns - 4 ) ); } else { this.effects.clack.log.error( wrapAnsi( `Could not create app: ${error instanceof Error ? error.message : error}`, this.effects.outputColumns ) ); } this.effects.clack.outro(yellow("Deploy canceled")); throw new CliError("Error during deploy", {cause: error, print: false}); } } await this.effects.setDeployConfig( this.deployOptions.config.root, this.deployOptions.deployConfigPath, { projectId: deployTarget.project.id, projectSlug: deployTarget.project.slug, workspaceLogin: deployTarget.workspace.login }, this.effects ); return deployTarget; }
// Get the deploy target, prompting the user as needed.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L277-L399
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.createNewDeploy
private async createNewDeploy(deployTarget: DeployTargetInfo): Promise<string> { if (deployTarget.create) { throw Error("Incorrect deployTarget state"); } let message = this.deployOptions.message; if (message === undefined) { if (this.effects.isTty) { const input = await this.effects.clack.text({ message: "What changed in this deploy?", placeholder: "Enter a deploy message (optional)" }); if (this.effects.clack.isCancel(input)) throw new CliError("User canceled deploy", {print: false, exitCode: 0}); message = input; } else { message = ""; } } let deployId; try { deployId = await this.apiClient.postDeploy({projectId: deployTarget.project.id, message}); } catch (error) { if (isHttpError(error)) { if (error.statusCode === 404) { throw new CliError( `App ${deployTarget.project.slug} in workspace @${deployTarget.workspace.login} not found.`, { cause: error } ); } else if (error.statusCode === 403) { throw new CliError( `You don't have permission to deploy to ${deployTarget.project.slug} in workspace @${deployTarget.workspace.login}.`, {cause: error} ); } } throw error; } return deployId; }
// Create the new deploy on the server.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L402-L444
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.getBuildFilePaths
private async getBuildFilePaths(): Promise<string[]> { let doBuild = this.deployOptions.force === "build"; let buildFilePaths: string[] | null = null; // Check if the build is missing. If it is present, then continue; otherwise // if --no-build was specified, then error; otherwise if in a tty, ask the // user if they want to build; otherwise build automatically. try { buildFilePaths = await this.findBuildFiles(); } catch (error) { if (CliError.match(error, {message: /No build files found/})) { if (this.deployOptions.force === "deploy") { throw new CliError("No build files found."); } else if (!this.deployOptions.force) { if (this.effects.isTty) { const choice = await this.effects.clack.confirm({ message: "No build files found. Do you want to build the app now?", active: "Yes, build and then deploy", inactive: "No, cancel deploy" }); if (this.effects.clack.isCancel(choice) || !choice) { throw new CliError("User canceled deploy", {print: false, exitCode: 0}); } } doBuild = true; } } else { throw error; } } // If we haven’t decided yet whether or not we’re building, check how old the // build is, and whether it is stale (i.e., whether the source files are newer // than the build). If in a tty, ask the user if they want to build; otherwise // deploy as is. if (!doBuild && !this.deployOptions.force && this.effects.isTty) { const leastRecentBuildMtimeMs = await this.findLeastRecentBuildMtimeMs(); const mostRecentSourceMtimeMs = await this.findMostRecentSourceMtimeMs(); const buildAge = Date.now() - leastRecentBuildMtimeMs; let initialValue = buildAge > BUILD_AGE_WARNING_MS; if (mostRecentSourceMtimeMs > leastRecentBuildMtimeMs) { this.effects.clack.log.warn( wrapAnsi(`Your source files have changed since you built ${formatAge(buildAge)}.`, this.effects.outputColumns) ); initialValue = true; } else { this.effects.clack.log.info(wrapAnsi(`You built this app ${formatAge(buildAge)}.`, this.effects.outputColumns)); } const choice = await this.effects.clack.confirm({ message: "Would you like to build again before deploying?", initialValue, active: "Yes, build and then deploy", inactive: "No, deploy as is" }); if (this.effects.clack.isCancel(choice)) throw new CliError("User canceled deploy", {print: false, exitCode: 0}); doBuild = !!choice; } if (doBuild) { this.effects.clack.log.step("Building app"); await this.effects.build( {config: this.deployOptions.config}, new FileBuildEffects( this.deployOptions.config.output, join(this.deployOptions.config.root, ".observablehq", "cache"), { logger: this.effects.logger, output: this.effects.output } ) ); buildFilePaths = await this.findBuildFiles(); } if (!buildFilePaths) throw new Error("No build files found."); return buildFilePaths; }
// Get the list of build files, doing a build if necessary.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L447-L523
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
getDuckDBExtension
async function getDuckDBExtension(root: string, href: string | URL, aliases?: Map<string, string>) { let ext = await cacheDuckDBExtension(root, href); if (aliases?.has(ext)) ext = aliases.get(ext)!; return join("..", "..", dirname(dirname(dirname(ext)))); }
/** * Returns the extension “custom repository” location as needed for DuckDB’s * INSTALL command. This is the relative path to which DuckDB will implicitly add * v{version}/wasm_{platform}/{name}.duckdb_extension.wasm, assuming that the * manifest is baked into /_observablehq/stdlib/duckdb.js. * * https://duckdb.org/docs/extensions/working_with_extensions#creating-a-custom-repository */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/duckdb.ts#L93-L97
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
CliError.assert
static assert( error: unknown, {message, exitCode = 1, print = true}: {message?: RegExp | string; exitCode?: number; print?: boolean} = {} ): asserts error is CliError { assert.ok(error instanceof Error, `Expected error to be an Error but got ${error}`); assert.ok(error instanceof CliError, `Expected error to be a CliError but got ${error.message}\n${error.stack}`); if (typeof message === "string") { assert.equal(error.message, message); } else if (message instanceof RegExp) { assert.ok( message.test(error.message), `Expected error message to match regexp ${message.toString()} but got ${error.message}` ); } assert.equal(error.exitCode, exitCode, `Expected exit code to be ${exitCode}, but got ${error.exitCode}`); assert.equal(error.print, print, `Expected print to be ${print}, but got ${error.print}`); }
/** Use in tests to check if a thrown error is the error you expected. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/error.ts#L62-L78
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
CliError.match
static match( error: unknown, {message, exitCode, print}: {message?: RegExp | string; exitCode?: number; print?: boolean} = {} ): error is CliError { if (!(error instanceof Error)) return false; if (!(error instanceof CliError)) return false; if (message !== undefined && typeof message === "string" && error.message !== message) return false; if (message !== undefined && message instanceof RegExp && !message.test(error.message)) return false; if (exitCode !== undefined && error.exitCode !== exitCode) return false; if (print !== undefined && error.print !== print) return false; return true; }
/** Use in tests to check if a thrown error is the error you expected. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/error.ts#L81-L92
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
resolveJsrVersion
async function resolveJsrVersion(root: string, {name, range}: NpmSpecifier): Promise<string> { const cache = await getJsrVersionCache(root); const versions = cache.get(name); if (versions) for (const version of versions) if (!range || satisfies(version, range)) return version; const href = `https://npm.jsr.io/@jsr/${name.replace(/^@/, "").replace(/\//, "__")}`; let promise = jsrVersionRequests.get(href); if (promise) return promise; // coalesce concurrent requests promise = (async function () { process.stdout.write(`jsr:${formatNpmSpecifier({name, range})} ${faint("→")} `); const metaResponse = await fetch(href); if (!metaResponse.ok) throw new Error(`unable to fetch: ${href}`); const meta = await metaResponse.json(); let info: {version: string; dist: {tarball: string}} | undefined; if (meta["dist-tags"][range ?? "latest"]) { info = meta["versions"][meta["dist-tags"][range ?? "latest"]]; } else if (range) { if (meta.versions[range]) { info = meta.versions[range]; // exact match; ignore yanked } else { for (const key in meta.versions) { if (satisfies(key, range) && !meta.versions[key].yanked) { info = meta.versions[key]; } } } } if (!info) throw new Error(`unable to resolve version: ${formatNpmSpecifier({name, range})}`); const {version, dist} = info; await fetchJsrPackage(root, name, version, dist.tarball); cache.set(name, versions ? rsort(versions.concat(version)) : [version]); process.stdout.write(`${version}\n`); return version; })(); promise.catch(console.error).then(() => jsrVersionRequests.delete(href)); jsrVersionRequests.set(href, promise); return promise; }
/** * Resolves the desired version of the specified JSR package, respecting the * specifier’s range if any. If any satisfying packages already exist in the JSR * import cache, the greatest satisfying cached version is returned. Otherwise, * the desired version is resolved via JSR’s API, and then the package and all * its transitive dependencies are downloaded from JSR (and npm if needed). */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/jsr.ts#L35-L71
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
fetchJsrPackage
async function fetchJsrPackage(root: string, name: string, version: string, tarball: string): Promise<void> { const dir = join(root, ".observablehq", "cache", "_jsr", formatNpmSpecifier({name, range: version})); let promise = jsrPackageRequests.get(dir); if (promise) return promise; promise = (async () => { const tarballResponse = await fetch(tarball); if (!tarballResponse.ok) throw new Error(`unable to fetch: ${tarball}`); await mkdir(dir, {recursive: true}); await finished(Readable.fromWeb(tarballResponse.body as any).pipe(x({strip: 1, C: dir}))); await rewriteJsrImports(root, dir); })(); promise.catch(console.error).then(() => jsrPackageRequests.delete(dir)); jsrPackageRequests.set(dir, promise); return promise; }
/** * Fetches a package from the JSR registry, as well as its transitive * dependencies from JSR and npm, rewriting any dependency imports as relative * paths within the import cache. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/jsr.ts#L78-L92
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
rewriteJsrImports
async function rewriteJsrImports(root: string, dir: string): Promise<void> { const info = JSON.parse(await readFile(join(dir, "package.json"), "utf8")); for (const path of globSync("**/*.js", {cwd: dir, nodir: true})) { const input = await readFile(join(dir, path), "utf8"); const promises = new Map<string, Promise<string>>(); try { rewriteNpmImports(input, (i) => { if (i.startsWith("@jsr/")) { const {name, path} = parseNpmSpecifier(i); const range = resolveDependencyVersion(info, name); const specifier = formatNpmSpecifier({name: `@${name.slice("@jsr/".length).replace(/__/, "/")}`, range, path}); // prettier-ignore if (!promises.has(i)) promises.set(i, resolveJsrImport(root, specifier)); } else if (!isPathImport(i) && !/^[\w-]+:/.test(i)) { const {name, path} = parseNpmSpecifier(i); const range = resolveDependencyVersion(info, i); const specifier = formatNpmSpecifier({name, range, path}); if (!promises.has(i)) promises.set(i, resolveNpmImport(root, specifier)); } }); } catch { continue; // ignore syntax errors } const resolutions = new Map<string, string>(); for (const [key, promise] of promises) resolutions.set(key, await promise); const output = rewriteNpmImports(input, (i) => resolutions.get(i)); await writeFile(join(dir, path), output, "utf8"); } }
/** * After downloading a package from JSR, this rewrites any transitive JSR and * Node imports to use relative paths within the import cache. For example, if * jsr:@std/streams depends on jsr:@std/bytes, this will replace an import of * @jsr/std__bytes with a relative path to /_jsr/@std/bytes@1.0.2/mod.js. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/jsr.ts#L124-L151
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
resolveDependencyVersion
function resolveDependencyVersion(info: PackageInfo, name: string): string | undefined { return ( info.dependencies?.[name] ?? info.devDependencies?.[name] ?? info.peerDependencies?.[name] ?? info.optionalDependencies?.[name] ?? info.bundleDependencies?.[name] ?? info.bundledDependencies?.[name] ); }
// https://docs.npmjs.com/cli/v10/configuring-npm/package-json
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/jsr.ts#L165-L174
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.loadPage
async loadPage(path: string, options: LoadOptions & ParseOptions, effects?: LoadEffects): Promise<MarkdownPage> { const loader = this.findPage(path); if (!loader) throw enoent(path); const input = await readFile(join(this.root, await loader.load(options, effects)), "utf8"); return parseMarkdown(input, {source: loader.path, params: loader.params, ...options}); }
/** * Loads the page at the specified path, returning a promise to the parsed * page object. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L80-L85
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.watchPage
watchPage(path: string, listener: WatchListener<string>): FSWatcher { const loader = this.findPage(path); if (!loader) throw enoent(path); return watch(join(this.root, loader.path), listener); }
/** * Returns a watcher for the page at the specified path. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L90-L94
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.findPagePaths
*findPagePaths(): Generator<string> { const ext = new RegExp(`\\.md(${["", ...this.interpreters.keys()].map(requote).join("|")})$`); for (const file of visitFiles(this.root, (name) => !isParameterized(name))) { if (!ext.test(file)) continue; const path = `/${file.slice(0, file.lastIndexOf(".md"))}`; if (extname(path) === ".js" && findModule(this.root, path)) continue; yield path; } }
/** * Finds the paths of all non-parameterized pages within the source root. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L99-L107
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.findPage
findPage(path: string): Loader | undefined { if (extname(path) === ".js" && findModule(this.root, path)) return; return this.find(`${path}.md`); }
/** * Finds the page loader for the specified target path, relative to the source * root, if the loader exists. If there is no such loader, returns undefined. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L113-L116
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.find
find(path: string): Loader | undefined { return this.findFile(path) ?? this.findArchive(path); }
/** * Finds the loader for the specified target path, relative to the source * root, if the loader exists. If there is no such loader, returns undefined. * For files within archives, we find the first parent folder that exists, but * abort if we find a matching folder or reach the source root; for example, * if src/data exists, we won’t look for a src/data.zip. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L125-L127
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.findFile
private findFile(targetPath: string): Loader | undefined { const ext = extname(targetPath); const exts = ext ? [ext, ...Array.from(this.interpreters.keys(), (iext) => ext + iext)] : [ext]; const found = route(this.root, ext ? targetPath.slice(0, -ext.length) : targetPath, exts); if (!found) return; const {path, params, ext: fext} = found; if (fext === ext) return new StaticLoader({root: this.root, path, params}); const commandPath = join(this.root, path); const [command, ...args] = this.interpreters.get(fext.slice(ext.length))!; if (command != null) args.push(commandPath); return new CommandLoader({ command: command ?? commandPath, args: params ? args.concat(defineParams(params)) : args, path, params, root: this.root, targetPath }); }
// - /[param1]/[param2]/[param3].csv.js
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L146-L164
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.findArchive
private findArchive(targetPath: string): Loader | undefined { const exts = this.getArchiveExtensions(); for (let dir = dirname(targetPath), parent: string; (parent = dirname(dir)) !== dir; dir = parent) { const found = route(this.root, dir, exts); if (!found) continue; const {path, params, ext: fext} = found; const inflatePath = targetPath.slice(dir.length + 1); // file.jpeg if (extractors.has(fext)) { const Extractor = extractors.get(fext)!; return new Extractor({ preload: async () => path, // /path/to.zip inflatePath, path, params, root: this.root, targetPath // /path/to/file.jpg }); } const iext = extname(fext); const commandPath = join(this.root, path); const [command, ...args] = this.interpreters.get(iext)!; if (command != null) args.push(commandPath); const eext = fext.slice(0, -iext.length); // .zip const loader = new CommandLoader({ command: command ?? commandPath, args: params ? args.concat(defineParams(params)) : args, path, params, root: this.root, targetPath: dir + eext // /path/to.zip }); const Extractor = extractors.get(eext)!; return new Extractor({ preload: async (options, effects) => loader.load(options, effects), // /path/to.zip.js inflatePath, path: loader.path, params, root: this.root, targetPath }); } }
// - /[param].tgz.js
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L191-L232
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.getArchiveExtensions
getArchiveExtensions(): string[] { const exts = Array.from(extractors.keys()); for (const e of extractors.keys()) for (const i of this.interpreters.keys()) exts.push(e + i); return exts; }
// .zip, .tar, .tgz, .zip.js, .zip.py, etc.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L235-L239
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.getWatchPath
getWatchPath(path: string): string | undefined { const exactPath = join(this.root, path); if (existsSync(exactPath)) return exactPath; if (exactPath.endsWith(".js")) { const module = findModule(this.root, path); return module && join(this.root, module.path); } const foundPath = this.find(path)?.path; if (foundPath) return join(this.root, foundPath); }
/** * Returns the path to watch, relative to the current working directory, for * the specified source path, relative to the source root. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L245-L254
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.getSourceFilePath
private getSourceFilePath(path: string): string { if (!existsSync(join(this.root, path))) { const loader = this.find(path); if (loader) return loader.path; } return path; }
/** * Returns the path to the backing file during preview, relative to the source * root, which is the source file for the associated data loader if the file * is generated by a loader. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L265-L271
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.getOutputFilePath
private getOutputFilePath(path: string): string { if (!existsSync(join(this.root, path))) { const loader = this.find(path); if (loader) return join(".observablehq", "cache", path); } return path; }
/** * Returns the path to the backing file during build, relative to the source * root, which is the cached output file if the file is generated by a loader. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L277-L283
82412a49f495a018367fc569f0407e06bae3479f