prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack | .parseLine(extra.stack.split('\n')[0])
} |
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 40.178359007577505
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " file,\n line: er.loc.line,\n column: er.loc.column + 1,\n }\n } else {\n // parse out the 'at' bit from the first line.\n extra.at = stack.parseLine(splitst[1])\n }\n extra.stack = stack.clean(splitst)\n }",
"score": 38.9004099150746
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (!er || typeof er !== 'object') {\n extra.error = er\n return extra\n }\n // pull out error details\n const message = er.message ? er.message\n : er.stack ? er.stack.split('\\n')[0]\n : ''\n if (er.message) {\n try {",
"score": 33.67594970693944
},
{
"filename": "src/base.ts",
"retrieved_chunk": " } else if (!er.stack) {\n console.error(er)\n } else {\n if (message) {\n er.message = message\n }\n delete extra.stack\n delete extra.at\n console.error('%s: %s', er.name || 'Error', message)\n console.error(",
"score": 31.54166321946662
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 31.14822642518369
}
] | typescript | .parseLine(extra.stack.split('\n')[0])
} |
// This file is automatically generated, please do not edit
import { FinalResults } from 'tap-parser'
import parseTestArgs, {
TestArgs,
} from './parse-test-args.js'
import { TestBase, TestBaseOpts } from './test-base.js'
const copyToString = (v: Function) => ({
toString: Object.assign(() => v.toString(), {
toString: () => 'function toString() { [native code] }',
}),
})
import plugin0 from "./plugin/after-each.js"
import plugin1 from "./plugin/before-each.js"
import plugin2 from "./plugin/spawn.js"
import plugin3 from "./plugin/stdin.js"
type PI<O extends TestBaseOpts | any = any> =
| ((t: Test, opts: O) => Plug)
| ((t: Test) => Plug)
const plugins: PI[] = [
plugin0,
plugin1,
plugin2,
plugin3,
]
type Plug =
| TestBase
| { t: Test }
| ReturnType<typeof plugin0>
| ReturnType<typeof plugin1>
| ReturnType<typeof plugin2>
| ReturnType<typeof plugin3>
type PlugKeys =
| keyof TestBase
| 't'
| keyof ReturnType<typeof plugin0>
| keyof ReturnType<typeof plugin1>
| keyof ReturnType<typeof plugin2>
| keyof ReturnType<typeof plugin3>
type SecondParam<
T extends [any] | [any, any],
Fallback extends unknown = unknown
> = T extends [any, any] ? T[1] : Fallback
type Plugin0Opts = SecondParam<
Parameters<typeof plugin0>,
TestBaseOpts
>
type Plugin1Opts = SecondParam<
Parameters<typeof plugin1>,
TestBaseOpts
>
type Plugin2Opts = SecondParam<
Parameters<typeof plugin2>,
TestBaseOpts
>
type Plugin3Opts = SecondParam<
Parameters<typeof plugin3>,
TestBaseOpts
>
type TestOpts = TestBaseOpts
& Plugin0Opts
& Plugin1Opts
& Plugin2Opts
& Plugin3Opts
type TTest = TestBase
& ReturnType<typeof plugin0>
& ReturnType<typeof plugin1>
& ReturnType<typeof plugin2>
& ReturnType | <typeof plugin3>
export interface Test extends TTest { |
end(): this
t: Test
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null>
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null>
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null>
}
const applyPlugins = (base: Test): Test => {
const ext: Plug[] = [
...plugins.map(p => p(base, base.options)),
base,
]
const getCache = new Map<any, any>()
const t = new Proxy(base, {
has(_, p) {
for (const t of ext) {
if (Reflect.has(t, p)) return true
}
return false
},
ownKeys() {
const k: PlugKeys[] = []
for (const t of ext) {
const keys = Reflect.ownKeys(t) as PlugKeys[]
k.push(...keys)
}
return [...new Set(k)]
},
getOwnPropertyDescriptor(_, p) {
for (const t of ext) {
const prop = Reflect.getOwnPropertyDescriptor(t, p)
if (prop) return prop
}
return undefined
},
set(_, p, v) {
// check to see if there's any setters, and if so, set it there
// otherwise, just set on the base
for (const t of ext) {
let o: Object | null = t
while (o) {
if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {
//@ts-ignore
t[p] = v
return true
}
o = Reflect.getPrototypeOf(o)
}
}
//@ts-ignore
base[p as keyof TestBase] = v
return true
},
get(_, p) {
// cache get results so t.blah === t.blah
// we only cache functions, so that getters aren't memoized
// Of course, a getter that returns a function will be broken,
// at least when accessed from outside the plugin, but that's
// a pretty narrow caveat, and easily documented.
if (getCache.has(p)) return getCache.get(p)
for (const plug of ext) {
if (p in plug) {
//@ts-ignore
const v = plug[p]
// Functions need special handling so that they report
// the correct toString and are called on the correct object
// Otherwise attempting to access #private props will fail.
if (typeof v === 'function') {
const f: (this: Plug, ...args: any) => any =
function (...args: any[]) {
const thisArg = this === t ? plug : this
return v.apply(thisArg, args)
}
const vv = Object.assign(f, copyToString(v))
const nameProp =
Reflect.getOwnPropertyDescriptor(v, 'name')
if (nameProp) {
Reflect.defineProperty(f, 'name', nameProp)
}
getCache.set(p, vv)
return vv
} else {
getCache.set(p, v)
return v
}
}
}
},
})
Object.assign(base, { t })
ext.unshift({ t })
return t
}
export class Test extends TestBase {
constructor(opts: TestOpts) {
super(opts)
return applyPlugins(this)
}
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.test)
}
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.todo)
}
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.skip = true
return this.sub(Test, extra, this.skip)
}
}
| src/test-built.ts | tapjs-core-edd7403 | [
{
"filename": "src/build.ts",
"retrieved_chunk": " .join('')}\ntype TestOpts = TestBaseOpts${plugins\n .map((_, i) => `\\n & Plugin${i}Opts`)\n .join('')}\n`\nconst testInterface = `type TTest = TestBase\n${plugins\n .map((_, i) => ` & ReturnType<typeof plugin${i}>\\n`)\n .join('')}\n`",
"score": 39.411112842705144
},
{
"filename": "src/build.ts",
"retrieved_chunk": " .join('')}\ntype PlugKeys =\n | keyof TestBase\n | 't'\n${plugins\n .map(\n (_, i) => ` | keyof ReturnType<typeof plugin${i}>\\n`\n )\n .join('')}`\nconst opts = `type SecondParam<",
"score": 34.0731816094973
},
{
"filename": "src/build.ts",
"retrieved_chunk": " `import plugin${i} from ${JSON.stringify(p)}\\n`\n )\n .join('')\nconst pluginsCode = `const plugins: PI[] = [\n${plugins.map((_, i) => ` plugin${i},\\n`).join('')}]\ntype Plug =\n | TestBase\n | { t: Test }\n${plugins\n .map((_, i) => ` | ReturnType<typeof plugin${i}>\\n`)",
"score": 27.930279187477534
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{TEST INTERFACE END}}\nexport interface Test extends TTest {\n end(): this\n t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 20.125912105414653
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 18.662906874977892
}
] | typescript | <typeof plugin3>
export interface Test extends TTest { |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML | = CopyIcon
actionButton.onclick = () => { |
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\"Mentor\",\n\t\t\t(evt: MouseEvent) => {\n\t\t\t\t// Called when the user clicks the icon.\n\t\t\t\tthis.activateView()\n\t\t\t}\n\t\t)\n\t\t// Perform additional things with the ribbon\n\t\tribbonIconEl.addClass(\"mentor-ribbon\")\n\t\t// This adds a settings tab so the user can configure various aspects of the plugin\n\t\tthis.addSettingTab(new SettingTab(this.app, this))",
"score": 31.85680603897765
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\t\tthis.plugin.settings.token = change\n\t\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t\t})\n\t\t\t})\n\t\t\t.addButton((button: ButtonComponent) => {\n\t\t\t\tbutton.setButtonText(\"Generate token\")\n\t\t\t\tbutton.onClick((evt: MouseEvent) => {\n\t\t\t\t\twindow.open(\"https://platform.openai.com/account/api-keys\")\n\t\t\t\t})\n\t\t\t})",
"score": 30.899514187525053
},
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\tconst { contentEl } = this\n\t\tconst titleEl = contentEl.createDiv(\"title\")\n\t\ttitleEl.addClass(\"modal__title\")\n\t\ttitleEl.setText(this.title)\n\t\tconst textEl = contentEl.createDiv(\"text\")\n\t\ttextEl.addClass(\"modal__text\")\n\t\ttextEl.setText(this.displayedText)\n\t\t// Copy text when clicked\n\t\ttextEl.addEventListener(\"click\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)",
"score": 23.136282397673952
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\tthis.settings.token,\n\t\t\t\t\tthis.settings.preferredMentorId,\n\t\t\t\t\tthis.settings.model,\n\t\t\t\t\tthis.settings.language\n\t\t\t\t)\n\t\t)\n\t\t// This creates an icon in the left ribbon.\n\t\taddIcon(\"aimentor\", MentorIcon)\n\t\tconst ribbonIconEl = this.addRibbonIcon(\n\t\t\t\"aimentor\",",
"score": 21.693894991935352
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 16.19828112241347
}
] | typescript | = CopyIcon
actionButton.onclick = () => { |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl. | text = mentor[1].name[this.preferredLanguage]
} |
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 36.33547841337662
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tconst requestedMentor = mentorList[command.mentor]\n\t\tconst prompts = command.pattern.map((prompt) => {\n\t\t\treturn prompt[this.preferredLanguage].replace(\"*\", text)\n\t\t})\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: requestedMentor.systemPrompt[this.preferredLanguage],\n\t\t\t},\n\t\t\tcommand.prompt[this.preferredLanguage],",
"score": 16.818525737963984
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tmentor: Mentor,\n\t\tmodel: ModelType,\n\t\tapiKey: string,\n\t\tpreferredLanguage: supportedLanguage,\n\t\tsuffix?: string\n\t) {\n\t\tthis.id = id\n\t\tthis.mentor = mentor\n\t\tthis.model = model\n\t\tthis.apiKey = apiKey",
"score": 12.981762554817989
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\tcontent: newMentor.systemPrompt[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t}\n\treset() {\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: this.mentor.systemPrompt[this.preferredLanguage],\n\t\t\t},",
"score": 12.507729158598124
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t.setDesc(\"The mentor you'd like to talk to in priority.\")\n\t\t\t.addDropdown((dropdown) => {\n\t\t\t\tmentorIds.forEach((id) => {\n\t\t\t\t\tdropdown.addOption(id, mentorList[id].name.en)\n\t\t\t\t})\n\t\t\t\tdropdown.setValue(\n\t\t\t\t\tthis.plugin.settings.preferredMentorId || \"default\"\n\t\t\t\t)\n\t\t\t\tdropdown.onChange((value) => {\n\t\t\t\t\tthis.plugin.settings.preferredMentorId = value",
"score": 12.266866718087932
}
] | typescript | text = mentor[1].name[this.preferredLanguage]
} |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
| .then(async (response) => { |
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 33.65916065611256
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t]\n\t\tconst answers: string[] = []\n\t\tfor (const prompt of prompts) {\n\t\t\tthis.history.push({ role: \"user\", content: prompt })\n\t\t\tconst body = {\n\t\t\t\tmessages: this.history,\n\t\t\t\tmodel: this.model,\n\t\t\t\t...pythonifyKeys(params),\n\t\t\t\tstop: params.stop.length > 0 ? params.stop : undefined,\n\t\t\t\tsuffix: this.suffix,",
"score": 26.12764791739322
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 24.191353175115765
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tconst requestedMentor = mentorList[command.mentor]\n\t\tconst prompts = command.pattern.map((prompt) => {\n\t\t\treturn prompt[this.preferredLanguage].replace(\"*\", text)\n\t\t})\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: requestedMentor.systemPrompt[this.preferredLanguage],\n\t\t\t},\n\t\t\tcommand.prompt[this.preferredLanguage],",
"score": 22.856671572606903
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tDEFAULT_SETTINGS,\n\t\t\tawait this.loadData()\n\t\t)\n\t}\n\tasync saveSettings() {\n\t\tawait this.saveData(this.settings)\n\t}\n\tasync getCompletion() {\n\t\tconsole.log(\"OK\")\n\t}",
"score": 21.670936835932846
}
] | typescript | .then(async (response) => { |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
| this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({ |
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 24.937824184483024
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t// Check that the message is not empty\n\t\tif (!message) {\n\t\t\treturn \"Please enter a message.\"\n\t\t}\n\t\tconst messages = [...this.history, { role: \"user\", content: message }]\n\t\tconst body = {\n\t\t\tmessages,\n\t\t\tmodel: this.model,\n\t\t\t...pythonifyKeys(params),\n\t\t\tstop: params.stop.length > 0 ? params.stop : undefined,",
"score": 24.382204185984165
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t// Add a send button.\n\t\tconst sendButton = interationDiv.createEl(\"button\")\n\t\tsendButton.addClass(\"icon-button\")\n\t\tsendButton.addClass(\"clickable-icon\")\n\t\tsendButton.innerHTML = SendIcon\n\t\tsendButton.onclick = () => this.handleSend()\n\t\t// Add a button to clear the chat.\n\t\tconst clearButton = interationDiv.createEl(\"button\")\n\t\tclearButton.addClass(\"icon-button\")\n\t\tclearButton.addClass(\"clickable-icon\")",
"score": 23.91522673420259
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tthis.mentor.history.length !== 0 &&\n\t\t\tthis.mentor.history[this.mentor.history.length - 1].role === \"user\"\n\t\t) {\n\t\t\tnew Notice(\"Please wait for your mentor to respond.\")\n\t\t\treturn\n\t\t}\n\t\tconst prompt = await this.handleKeywordsInPrompt(this.currentInput)\n\t\t// Display the prompt\n\t\tthis.displayedMessages.push({\n\t\t\trole: \"user\",",
"score": 23.894362416129045
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "import { Mentor, supportedLanguage } from \"./types\"\nexport default class SettingTab extends PluginSettingTab {\n\tplugin: ObsidianMentor\n\tconstructor(app: App, plugin: ObsidianMentor) {\n\t\tsuper(app, plugin)\n\t\tthis.plugin = plugin\n\t}\n\tdisplay(): void {\n\t\tconst { containerEl } = this\n\t\tcontainerEl.empty()",
"score": 22.464293646594196
}
] | typescript | this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({ |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
| const params = command.settings
const mentorList: Record<string, Mentor> = { |
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => {
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/ai/commands.ts",
"retrieved_chunk": "import { GPTSettings } from \"./model\"\nimport { Message, MultiLingualString, supportedLanguage } from \"../types\"\nexport interface Command {\n\tmentor: string\n\tprompt: Record<supportedLanguage, Message>\n\tpattern: MultiLingualString[]\n\tsettings: GPTSettings\n}\nexport const commands: Record<string, Command> = {\n\texplain: {",
"score": 22.93331999602267
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t.catch(async (error) => {\n\t\t\t\tconsole.log(\"error\", error)\n\t\t\t\t// Clear the input.\n\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the error message.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"An error occurred. Please try again.\",\n\t\t\t\t})",
"score": 22.197104656307552
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 22.008537384702162
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\tpreferredLanguage = \"en\"\n\tmodel: ModelType\n\tfirstOpen = true\n\t// isTyping = false\n\tdisplayedMessages: Message[] = []\n\t// Merge the two Record<string, Mentor> objects into one.\n\tmentorList: Record<string, Mentor> = {\n\t\t...Topics,\n\t\t...Individuals,\n\t}",
"score": 21.060827556847446
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 20.09301220166467
}
] | typescript | const params = command.settings
const mentorList: Record<string, Mentor> = { |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
| .then((response) => { |
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "import { App, Modal, Notice } from \"obsidian\"\nexport class MentorModal extends Modal {\n\ttitle = \"\"\n\tdisplayedText = \"\"\n\tconstructor(app: App, title: string, displayedText: string) {\n\t\tsuper(app)\n\t\tthis.title = title\n\t\tthis.displayedText = displayedText\n\t}\n\tonOpen() {",
"score": 13.935624889792278
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tif (prompt.includes(\"@current-note\")) {\n\t\t\tconst noteFile = this.app.workspace.getActiveFile()\n\t\t\tif (!noteFile || !noteFile.name) {\n\t\t\t\tnew Notice(\"Please open a note to use @current-note.\")\n\t\t\t\treturn prompt\n\t\t\t}\n\t\t\tconst text = await this.app.vault.read(noteFile)\n\t\t\tprompt = prompt.replace(\"@current-note\", text)\n\t\t\treturn prompt\n\t\t}",
"score": 13.571042448689559
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tthis.preferredLanguage = preferredLanguage\n\t\tthis.model = model\n\t\t// Mentor selection.\n\t\tconst selectedMentor = this.mentorList[preferredMentorId]\n\t\tthis.mentor = new MentorModel(\n\t\t\tpreferredMentorId,\n\t\t\tselectedMentor,\n\t\t\tthis.model,\n\t\t\ttoken,\n\t\t\tpreferredLanguage",
"score": 12.89134769992435
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 10.965081388490187
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 9.804805100527567
}
] | typescript | .then((response) => { |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
const | prompts = command.pattern.map((prompt) => { |
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 32.299585073283616
},
{
"filename": "src/ai/commands.ts",
"retrieved_chunk": "import { GPTSettings } from \"./model\"\nimport { Message, MultiLingualString, supportedLanguage } from \"../types\"\nexport interface Command {\n\tmentor: string\n\tprompt: Record<supportedLanguage, Message>\n\tpattern: MultiLingualString[]\n\tsettings: GPTSettings\n}\nexport const commands: Record<string, Command> = {\n\texplain: {",
"score": 31.775750048229966
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\tpreferredLanguage = \"en\"\n\tmodel: ModelType\n\tfirstOpen = true\n\t// isTyping = false\n\tdisplayedMessages: Message[] = []\n\t// Merge the two Record<string, Mentor> objects into one.\n\tmentorList: Record<string, Mentor> = {\n\t\t...Topics,\n\t\t...Individuals,\n\t}",
"score": 31.202714141820806
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\"default\",\n\t\t\tIndividuals[\"default\"],\n\t\t\tthis.settings.model,\n\t\t\tthis.settings.token,\n\t\t\tthis.settings.language\n\t\t)\n\t\t// This adds the \"ELI5\" command.\n\t\tthis.addCommand({\n\t\t\tid: \"eli5\",\n\t\t\tname: \"ELI5\",",
"score": 21.46996452952931
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t// This adds a command that can be triggered with a hotkey.\n\t\tthis.addCommand({\n\t\t\tid: \"open-mentor\",\n\t\t\tname: \"Open Mentor\",\n\t\t\tcallback: () => {\n\t\t\t\tthis.activateView()\n\t\t\t},\n\t\t})\n\t\t// AI COMMANDS\n\t\tconst alfred = new MentorModel(",
"score": 21.174459588341772
}
] | typescript | prompts = command.pattern.map((prompt) => { |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor | = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => { |
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 32.299585073283616
},
{
"filename": "src/ai/commands.ts",
"retrieved_chunk": "import { GPTSettings } from \"./model\"\nimport { Message, MultiLingualString, supportedLanguage } from \"../types\"\nexport interface Command {\n\tmentor: string\n\tprompt: Record<supportedLanguage, Message>\n\tpattern: MultiLingualString[]\n\tsettings: GPTSettings\n}\nexport const commands: Record<string, Command> = {\n\texplain: {",
"score": 31.775750048229966
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\tpreferredLanguage = \"en\"\n\tmodel: ModelType\n\tfirstOpen = true\n\t// isTyping = false\n\tdisplayedMessages: Message[] = []\n\t// Merge the two Record<string, Mentor> objects into one.\n\tmentorList: Record<string, Mentor> = {\n\t\t...Topics,\n\t\t...Individuals,\n\t}",
"score": 31.202714141820806
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\"default\",\n\t\t\tIndividuals[\"default\"],\n\t\t\tthis.settings.model,\n\t\t\tthis.settings.token,\n\t\t\tthis.settings.language\n\t\t)\n\t\t// This adds the \"ELI5\" command.\n\t\tthis.addCommand({\n\t\t\tid: \"eli5\",\n\t\t\tname: \"ELI5\",",
"score": 21.46996452952931
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t// This adds a command that can be triggered with a hotkey.\n\t\tthis.addCommand({\n\t\t\tid: \"open-mentor\",\n\t\t\tname: \"Open Mentor\",\n\t\t\tcallback: () => {\n\t\t\t\tthis.activateView()\n\t\t\t},\n\t\t})\n\t\t// AI COMMANDS\n\t\tconst alfred = new MentorModel(",
"score": 21.174459588341772
}
] | typescript | = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => { |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => {
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command | .prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) { |
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tthis.mentor.history.length !== 0 &&\n\t\t\tthis.mentor.history[this.mentor.history.length - 1].role === \"user\"\n\t\t) {\n\t\t\tnew Notice(\"Please wait for your mentor to respond.\")\n\t\t\treturn\n\t\t}\n\t\tconst prompt = await this.handleKeywordsInPrompt(this.currentInput)\n\t\t// Display the prompt\n\t\tthis.displayedMessages.push({\n\t\t\trole: \"user\",",
"score": 24.590324761671223
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 24.24563729548378
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t// Display messages in the chat.\n\t\tconst chatDiv = container.createDiv()\n\t\tchatDiv.addClass(\"chat__messages\")\n\t\t// Add history to selectedMentor.firstMessage\n\t\t// const firstMessage: Message = {\n\t\t// \trole: \"assistant\",\n\t\t// \tcontent: selectedMentor.firstMessage[this.preferredLanguage],\n\t\t// }\n\t\t// Add the first message to the chat.\n\t\tconst history =",
"score": 19.62413813589753
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tthis.mentor.history.filter(\n\t\t\t\t(message: Message) => message.role !== \"system\"\n\t\t\t) || []\n\t\tfor (const message of this.displayedMessages) {\n\t\t\t// Contains text and icon.\n\t\t\tconst messageDiv = chatDiv.createDiv()\n\t\t\tmessageDiv.addClass(\"chat__message-container\")\n\t\t\tmessageDiv.addClass(`chat__message-container--${message.role}`)\n\t\t\t// Add the message text.\n\t\t\tconst messageEl = messageDiv.createEl(\"p\", {",
"score": 19.09238115378108
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent:\n\t\t\t\t\tthis.mentor.mentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n}",
"score": 17.941046227710995
}
] | typescript | .prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) { |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
. | execute(selection, commands.explain)
.then((response) => { |
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tthis.preferredLanguage = preferredLanguage\n\t\tthis.model = model\n\t\t// Mentor selection.\n\t\tconst selectedMentor = this.mentorList[preferredMentorId]\n\t\tthis.mentor = new MentorModel(\n\t\t\tpreferredMentorId,\n\t\t\tselectedMentor,\n\t\t\tthis.model,\n\t\t\ttoken,\n\t\t\tpreferredLanguage",
"score": 10.943523311102416
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 9.115998279562097
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 8.550397269594676
},
{
"filename": "src/ai/commands.ts",
"retrieved_chunk": "import { GPTSettings } from \"./model\"\nimport { Message, MultiLingualString, supportedLanguage } from \"../types\"\nexport interface Command {\n\tmentor: string\n\tprompt: Record<supportedLanguage, Message>\n\tpattern: MultiLingualString[]\n\tsettings: GPTSettings\n}\nexport const commands: Record<string, Command> = {\n\texplain: {",
"score": 8.40318659912649
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 8.348785951570235
}
] | typescript | execute(selection, commands.explain)
.then((response) => { |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
| .catch(async (error) => { |
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 35.65544623975288
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 31.896382033331708
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t})\n\t\t)\n\t}\n\tasync activateView() {\n\t\t// Pass token from settings to the view\n\t\tthis.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)\n\t\tawait this.app.workspace.getRightLeaf(false).setViewState({\n\t\t\ttype: VIEW_TYPE_CHAT,\n\t\t\tactive: true,\n\t\t})",
"score": 16.623485025134308
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tDEFAULT_SETTINGS,\n\t\t\tawait this.loadData()\n\t\t)\n\t}\n\tasync saveSettings() {\n\t\tawait this.saveData(this.settings)\n\t}\n\tasync getCompletion() {\n\t\tconsole.log(\"OK\")\n\t}",
"score": 14.621331494069448
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\t\talfred\n\t\t\t\t\t\t\t\t.execute(selection, commands.explain)\n\t\t\t\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\t\t\t\tif (response) {\n\t\t\t\t\t\t\t\t\t\t// Show the explanation\n\t\t\t\t\t\t\t\t\t\tloadingModal.close()\n\t\t\t\t\t\t\t\t\t\tnew MentorModal(\n\t\t\t\t\t\t\t\t\t\t\tthis.app,\n\t\t\t\t\t\t\t\t\t\t\ttitle,\n\t\t\t\t\t\t\t\t\t\t\tresponse[0] // Only one possible response",
"score": 14.030344651997067
}
] | typescript | .catch(async (error) => { |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
| .execute(selection, commands.enhance)
.then((response) => { |
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tif (prompt.includes(\"@current-note\")) {\n\t\t\tconst noteFile = this.app.workspace.getActiveFile()\n\t\t\tif (!noteFile || !noteFile.name) {\n\t\t\t\tnew Notice(\"Please open a note to use @current-note.\")\n\t\t\t\treturn prompt\n\t\t\t}\n\t\t\tconst text = await this.app.vault.read(noteFile)\n\t\t\tprompt = prompt.replace(\"@current-note\", text)\n\t\t\treturn prompt\n\t\t}",
"score": 19.59265289073468
},
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "import { App, Modal, Notice } from \"obsidian\"\nexport class MentorModal extends Modal {\n\ttitle = \"\"\n\tdisplayedText = \"\"\n\tconstructor(app: App, title: string, displayedText: string) {\n\t\tsuper(app)\n\t\tthis.title = title\n\t\tthis.displayedText = displayedText\n\t}\n\tonOpen() {",
"score": 13.935624889792278
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tthis.preferredLanguage = preferredLanguage\n\t\tthis.model = model\n\t\t// Mentor selection.\n\t\tconst selectedMentor = this.mentorList[preferredMentorId]\n\t\tthis.mentor = new MentorModel(\n\t\t\tpreferredMentorId,\n\t\t\tselectedMentor,\n\t\t\tthis.model,\n\t\t\ttoken,\n\t\t\tpreferredLanguage",
"score": 12.89134769992435
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 11.687242790062973
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 10.965081388490187
}
] | typescript | .execute(selection, commands.enhance)
.then((response) => { |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor | .changeIdentity(id, newMentor)
this.displayedMessages = [
{ |
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t// Reset history\n\t\tthis.reset()\n\t\treturn answers\n\t}\n\tchangeIdentity(id: string, newMentor: Mentor) {\n\t\tthis.id = id\n\t\tthis.mentor = newMentor\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",",
"score": 38.790226557181384
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t.setDesc(\"The mentor you'd like to talk to in priority.\")\n\t\t\t.addDropdown((dropdown) => {\n\t\t\t\tmentorIds.forEach((id) => {\n\t\t\t\t\tdropdown.addOption(id, mentorList[id].name.en)\n\t\t\t\t})\n\t\t\t\tdropdown.setValue(\n\t\t\t\t\tthis.plugin.settings.preferredMentorId || \"default\"\n\t\t\t\t)\n\t\t\t\tdropdown.onChange((value) => {\n\t\t\t\t\tthis.plugin.settings.preferredMentorId = value",
"score": 20.74006234746245
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tmentor: Mentor,\n\t\tmodel: ModelType,\n\t\tapiKey: string,\n\t\tpreferredLanguage: supportedLanguage,\n\t\tsuffix?: string\n\t) {\n\t\tthis.id = id\n\t\tthis.mentor = mentor\n\t\tthis.model = model\n\t\tthis.apiKey = apiKey",
"score": 20.730417442614694
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t)\n\t\t// This adds the \"redact\" command.\n\t\tthis.addCommand({\n\t\t\tid: \"redact\",\n\t\t\tname: \"Redact\",\n\t\t\teditorCallback: async (editor) => {",
"score": 18.863071520362134
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\tcontent: newMentor.systemPrompt[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t}\n\treset() {\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: this.mentor.systemPrompt[this.preferredLanguage],\n\t\t\t},",
"score": 18.06732604219016
}
] | typescript | .changeIdentity(id, newMentor)
this.displayedMessages = [
{ |
import { addIcon, Menu, Notice, Plugin } from "obsidian"
import { commands } from "./ai/commands"
import { Individuals } from "./ai/mentors"
import { MentorModel, ModelType } from "./ai/model"
import { MentorIcon } from "./assets/icons/mentor"
import { ChatView, VIEW_TYPE_CHAT } from "./components/chatview"
import { MentorModal } from "./components/modals"
import SettingTab from "./settings"
import { supportedLanguage } from "./types"
interface MentorSettings {
preferredMentorId: string
language: supportedLanguage
token: string
model: ModelType
}
const DEFAULT_SETTINGS: MentorSettings = {
preferredMentorId: "default",
language: "en",
token: "",
model: ModelType.Default,
}
export default class ObsidianMentor extends Plugin {
settings: MentorSettings = DEFAULT_SETTINGS
async onload() {
await this.loadSettings()
this.registerView(
VIEW_TYPE_CHAT,
(leaf) =>
new ChatView(
leaf,
this.settings.token,
this.settings.preferredMentorId,
this.settings.model,
this.settings.language
)
)
// This creates an icon in the left ribbon.
addIcon("aimentor", MentorIcon)
const ribbonIconEl = this.addRibbonIcon(
"aimentor",
"Mentor",
(evt: MouseEvent) => {
// Called when the user clicks the icon.
this.activateView()
}
)
// Perform additional things with the ribbon
ribbonIconEl.addClass("mentor-ribbon")
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SettingTab(this.app, this))
// This adds a command that can be triggered with a hotkey.
this.addCommand({
id: "open-mentor",
name: "Open Mentor",
callback: () => {
this.activateView()
},
})
// AI COMMANDS
const alfred = new MentorModel(
"default",
Individuals["default"],
this.settings.model,
this.settings.token,
this.settings.language
)
// This adds the "ELI5" command.
this.addCommand({
id: "eli5",
name: "ELI5",
editorCallback: async (editor) => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands | .explain)
.then((response) => { |
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice("Error: Could not get explanation.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add ELI5 to the right-click context menu
// todo: clean to avoid code duplication
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Explain Like I'm 5")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Explain Like I'm 5"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Interesting, let me think..."
)
if (selection) {
loadingModal.open()
// Get the explanation
alfred
.execute(selection, commands.explain)
.then((response) => {
if (response) {
// Show the explanation
loadingModal.close()
new MentorModal(
this.app,
title,
response[0] // Only one possible response
).open()
} else {
// Show an error
new Notice(
"Error: Could not get explanation."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "redact" command.
this.addCommand({
id: "redact",
name: "Redact",
editorCallback: async (editor) => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice("Error: Could not redact your note.")
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add redact to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Redact")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Redact"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"Let me read and redact your note..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.redact)
.then((response) => {
if (response) {
const redactedNote = response[0]
// append a new line to the end of the note
loadingModal.close()
const note =
selection +
"\n\n___\n\n" +
redactedNote +
"\n\n___\n\n"
editor.replaceSelection(note)
} else {
// Show an error
new Notice(
"Error: Could not redact your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
// This adds the "enhance" command.
this.addCommand({
id: "enhance",
name: "Enhance",
editorCallback: async (editor) => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] = response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
},
})
// Also add enhance to the right-click context menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu: Menu, editor, view) => {
menu.addItem((item) => {
item.setTitle("Enhance")
item.setIcon("aimentor")
item.onClick(() => {
const title = "Enhance my writing"
const selection = editor.getSelection()
const loadingModal = new MentorModal(
this.app,
title,
"I am enhancing what you wrote..."
)
if (selection) {
loadingModal.open()
// Get the redacted note
alfred
.execute(selection, commands.enhance)
.then((response) => {
if (response) {
const [enhancedText, explanations] =
response
// replace the selection with the enhanced text
loadingModal.close()
editor.replaceSelection(enhancedText)
new MentorModal(
this.app,
title,
explanations
).open()
} else {
// Show an error
new Notice(
"Error: Could not enhance your note."
)
}
})
} else {
new Notice("Error: No text selected.")
}
})
})
})
)
}
async activateView() {
// Pass token from settings to the view
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
await this.app.workspace.getRightLeaf(false).setViewState({
type: VIEW_TYPE_CHAT,
active: true,
})
this.app.workspace.revealLeaf(
this.app.workspace.getLeavesOfType(VIEW_TYPE_CHAT)[0]
)
}
onunload() {
this.app.workspace.detachLeavesOfType(VIEW_TYPE_CHAT)
}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
)
}
async saveSettings() {
await this.saveData(this.settings)
}
async getCompletion() {
console.log("OK")
}
}
| src/main.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tthis.preferredLanguage = preferredLanguage\n\t\tthis.model = model\n\t\t// Mentor selection.\n\t\tconst selectedMentor = this.mentorList[preferredMentorId]\n\t\tthis.mentor = new MentorModel(\n\t\t\tpreferredMentorId,\n\t\t\tselectedMentor,\n\t\t\tthis.model,\n\t\t\ttoken,\n\t\t\tpreferredLanguage",
"score": 10.943523311102416
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tcontent: prompt,\n\t\t})\n\t\t// Add the loading message\n\t\tthis.displayedMessages.push(this.loadingMessage)\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t\tthis.mentor\n\t\t\t.getCompletion(prompt)\n\t\t\t.then(async (response) => {\n\t\t\t\t// Clear the input.",
"score": 9.115998279562097
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 8.550397269594676
},
{
"filename": "src/ai/commands.ts",
"retrieved_chunk": "import { GPTSettings } from \"./model\"\nimport { Message, MultiLingualString, supportedLanguage } from \"../types\"\nexport interface Command {\n\tmentor: string\n\tprompt: Record<supportedLanguage, Message>\n\tpattern: MultiLingualString[]\n\tsettings: GPTSettings\n}\nexport const commands: Record<string, Command> = {\n\texplain: {",
"score": 8.40318659912649
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 8.348785951570235
}
] | typescript | .explain)
.then((response) => { |
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Req,
} from '@nestjs/common';
import { Request } from 'express';
import { PostDocument } from 'src/common/schemas';
import { CreatePostDto } from 'src/common/dto';
import { PostService } from './post.service';
@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) {}
@Get('/id/:id')
getPost(@Param('id') id: string): Promise<PostDocument> {
return this.postService.getPostById(id);
}
@Get('/my')
getMyPost(@Req() request: Request): Promise<PostDocument[]> {
return this.postService.getMyPost(request.user);
}
@Post()
createPost(
@Req() request: Request,
@Body() data: CreatePostDto,
): Promise<PostDocument> {
return this.postService.createPost(data, request.user);
}
@Delete('/:id')
removePost(
@Req() request: Request,
@Param('id') id: string,
): Promise<boolean> {
return this.postService.removePost(id, request.user);
}
@Patch('/:id')
modifyPost(
@Req() request: Request,
@Param('id') id: string,
@Body() data: CreatePostDto,
): Promise<PostDocument> {
| return this.postService.modifyPost(data, id, request.user); |
}
}
| src/api/post/post.controller.ts | whguswo-trust-back-v1-b47407d | [
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " if (post.user.equals(user._id) && user.role !== 'ADMIN')\n throw new HttpException('Permission denied', 403);\n const result = await this.postModel.deleteOne({ _id });\n return result.deletedCount > 0;\n }\n async modifyPost(\n data: CreatePostDto,\n _id: string,\n user: UserDocument,\n ): Promise<PostDocument> {",
"score": 25.983877582062505
},
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " }\n async getMyPost(user: UserDocument): Promise<PostDocument[]> {\n const posts = await this.postModel.find({ user: user._id });\n return posts;\n }\n async getPostByUserId(_id: string): Promise<PostDocument[]> {\n const posts = await this.postModel.find({ user: new Types.ObjectId(_id) });\n return posts;\n }\n async createPost(data: CreatePostDto, user: UserDocument): Promise<PostDocument> {",
"score": 23.713955747336627
},
{
"filename": "src/api/user/user.controller.ts",
"retrieved_chunk": "@Controller('user')\nexport class UserController {\n constructor(private readonly userService: UserService) {}\n @Get()\n async getAllUser(): Promise<UserDocument[]> {\n return await this.userService.getAllUser();\n }\n @Post()\n async createUser(@Body() data: CreateUserDto): Promise<ResponseDto> {\n return await this.userService.createUser(data);",
"score": 20.677001469340595
},
{
"filename": "src/api/auth/auth.service.ts",
"retrieved_chunk": " ): Promise<boolean> {\n return bcrypt.compare(password + process.env.HASH_SALT, hashedPassword);\n }\n async login(data: LoginDto): Promise<UserDocument> {\n const user = await this.userModel.findOne({ username: data.username }).lean();\n if (!user) throw new HttpException('계정 또는 비밀번호가 잘못되었습니다.', 404);\n return user;\n }\n async getAccessToken(user: UserDocument): Promise<AccessTokenResponse> {\n delete user['password'];",
"score": 19.431010270594225
},
{
"filename": "src/api/auth/auth.controller.ts",
"retrieved_chunk": "@Controller('auth')\nexport class AuthController {\n constructor(private readonly authService: AuthService) {}\n @Post('/login')\n async login(@Body() data: LoginDto): Promise<AccessTokenResponse> {\n const user = await this.authService.login(data);\n return await this.authService.getAccessToken(user);\n }\n}",
"score": 19.280084182576154
}
] | typescript | return this.postService.modifyPost(data, id, request.user); |
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
. | getCompletion(prompt)
.then(async (response) => { |
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
| src/components/chatview.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tthis.history.push({ role: \"user\", content: message })\n\t\tconst answer = await request(requestUrlParam)\n\t\t\t.then((response) => {\n\t\t\t\tconst answer =\n\t\t\t\t\tJSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\t\treturn answer\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tconsole.error(err)",
"score": 28.055578409942555
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t\t\t.then((response) => {\n\t\t\t\t\treturn JSON.parse(response)?.choices?.[0]?.message?.content\n\t\t\t\t})\n\t\t\t\t.catch((err) => {\n\t\t\t\t\tconsole.error(err)\n\t\t\t\t\treturn \"I got an error when trying to reply.\"\n\t\t\t\t})\n\t\t\tthis.history.push({ role: \"assistant\", content: answer })\n\t\t\tanswers.push(answer)\n\t\t}",
"score": 22.202711569275692
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\tDEFAULT_SETTINGS,\n\t\t\tawait this.loadData()\n\t\t)\n\t}\n\tasync saveSettings() {\n\t\tawait this.saveData(this.settings)\n\t}\n\tasync getCompletion() {\n\t\tconsole.log(\"OK\")\n\t}",
"score": 21.670936835932846
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\t]\n\t\tconst answers: string[] = []\n\t\tfor (const prompt of prompts) {\n\t\t\tthis.history.push({ role: \"user\", content: prompt })\n\t\t\tconst body = {\n\t\t\t\tmessages: this.history,\n\t\t\t\tmodel: this.model,\n\t\t\t\t...pythonifyKeys(params),\n\t\t\t\tstop: params.stop.length > 0 ? params.stop : undefined,\n\t\t\t\tsuffix: this.suffix,",
"score": 21.19366249290538
},
{
"filename": "src/ai/model.ts",
"retrieved_chunk": "\t\tconst requestedMentor = mentorList[command.mentor]\n\t\tconst prompts = command.pattern.map((prompt) => {\n\t\t\treturn prompt[this.preferredLanguage].replace(\"*\", text)\n\t\t})\n\t\tthis.history = [\n\t\t\t{\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: requestedMentor.systemPrompt[this.preferredLanguage],\n\t\t\t},\n\t\t\tcommand.prompt[this.preferredLanguage],",
"score": 20.782015562230733
}
] | typescript | getCompletion(prompt)
.then(async (response) => { |
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Req,
} from '@nestjs/common';
import { Request } from 'express';
import { PostDocument } from 'src/common/schemas';
import { CreatePostDto } from 'src/common/dto';
import { PostService } from './post.service';
@Controller('post')
export class PostController {
constructor(private readonly postService: PostService) {}
@Get('/id/:id')
getPost(@Param('id') id: string): Promise<PostDocument> {
return this.postService.getPostById(id);
}
@Get('/my')
getMyPost(@Req() request: Request): Promise<PostDocument[]> {
return this.postService.getMyPost(request.user);
}
@Post()
createPost(
@Req() request: Request,
@Body() data: CreatePostDto,
): Promise<PostDocument> {
return this.postService.createPost(data, request.user);
}
@Delete('/:id')
removePost(
@Req() request: Request,
@Param('id') id: string,
): Promise<boolean> {
| return this.postService.removePost(id, request.user); |
}
@Patch('/:id')
modifyPost(
@Req() request: Request,
@Param('id') id: string,
@Body() data: CreatePostDto,
): Promise<PostDocument> {
return this.postService.modifyPost(data, id, request.user);
}
}
| src/api/post/post.controller.ts | whguswo-trust-back-v1-b47407d | [
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " }\n async getMyPost(user: UserDocument): Promise<PostDocument[]> {\n const posts = await this.postModel.find({ user: user._id });\n return posts;\n }\n async getPostByUserId(_id: string): Promise<PostDocument[]> {\n const posts = await this.postModel.find({ user: new Types.ObjectId(_id) });\n return posts;\n }\n async createPost(data: CreatePostDto, user: UserDocument): Promise<PostDocument> {",
"score": 26.7337524840897
},
{
"filename": "src/api/post/post.service.ts",
"retrieved_chunk": " const post = new this.postModel({\n ...data,\n user: new Types.ObjectId(user._id),\n });\n await post.save();\n return post;\n }\n async removePost(_id: string, user: UserDocument): Promise<boolean> {\n const post = await this.postModel.findById(new Types.ObjectId(_id));\n if (!post) throw new HttpException('해당 Post가 존재하지 않습니다.', 404);",
"score": 21.708806042077093
},
{
"filename": "src/api/user/user.controller.ts",
"retrieved_chunk": "@Controller('user')\nexport class UserController {\n constructor(private readonly userService: UserService) {}\n @Get()\n async getAllUser(): Promise<UserDocument[]> {\n return await this.userService.getAllUser();\n }\n @Post()\n async createUser(@Body() data: CreateUserDto): Promise<ResponseDto> {\n return await this.userService.createUser(data);",
"score": 20.677001469340595
},
{
"filename": "src/api/auth/auth.service.ts",
"retrieved_chunk": " ): Promise<boolean> {\n return bcrypt.compare(password + process.env.HASH_SALT, hashedPassword);\n }\n async login(data: LoginDto): Promise<UserDocument> {\n const user = await this.userModel.findOne({ username: data.username }).lean();\n if (!user) throw new HttpException('계정 또는 비밀번호가 잘못되었습니다.', 404);\n return user;\n }\n async getAccessToken(user: UserDocument): Promise<AccessTokenResponse> {\n delete user['password'];",
"score": 19.431010270594225
},
{
"filename": "src/api/auth/auth.controller.ts",
"retrieved_chunk": "@Controller('auth')\nexport class AuthController {\n constructor(private readonly authService: AuthService) {}\n @Post('/login')\n async login(@Body() data: LoginDto): Promise<AccessTokenResponse> {\n const user = await this.authService.login(data);\n return await this.authService.getAccessToken(user);\n }\n}",
"score": 19.280084182576154
}
] | typescript | return this.postService.removePost(id, request.user); |
import fs from 'node:fs';
import { join } from 'path';
import InternalDb from './db/InternalDb';
import { getActiveProjectId } from './db/localStorageUtils';
import { exportProject } from './exportData';
import { importProject, readProjectData } from './importData';
import renderModal from './ui/react/renderModal';
import confirmModal from './ui/react/confirmModal';
let prevExport = '';
export default async function autoExport() {
const projectId = getActiveProjectId();
if (!projectId) {
return;
}
const config = InternalDb.create();
const { repositoryPath: path, autoExport } = config.getProject(projectId);
if (!path || !autoExport || projectId === 'proj_default-project') {
return;
}
const [projectData, workspaces] = await exportProject(projectId);
const newExportJson = JSON.stringify([projectData, workspaces]);
if (newExportJson === prevExport) {
// Nothing to export, so lets try to Import
await autoImportProject(path);
return;
}
prevExport = newExportJson;
const targetFile = join(path, 'project.json');
fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));
for (const workspace of workspaces) {
const targetFile = join(path, workspace.id + '.json');
fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));
}
}
let prevImport = '';
async function autoImportProject(path: string) {
let project, workspaceData;
try {
[project, workspaceData] = readProjectData(path);
} catch (e) {
console.error('[IPGI] Error while gathering import data during auto import. This might not be a bug', e);
return;
}
const newImportJson = JSON.stringify([project, workspaceData]);
// Do not import the first time
if (prevImport === '') {
prevImport = newImportJson;
return;
}
if (prevImport === newImportJson) {
// Nothing to import
return;
}
const doImport = await | renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
)); |
if (!doImport) {
return;
}
await importProject(project, workspaceData);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
}
| src/autoExport.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [project, workspaceData] = readProjectData(path);\n await importProject(project, workspaceData);\n // Force Insomnia to read all data again.\n // Wrapped with requestIdleCallback to make sure NeDB had enough time to save everything\n // @ts-ignore\n window.requestIdleCallback(window.main.restart);",
"score": 18.066562761244242
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());\n workspaceData.push(workspace);\n }\n await importProject(project, workspaceData);\n // Force Insomnia to read all data again.\n // Wrapped with requestIdleCallback to make sure NeDB had enough time to save everything\n // @ts-ignore\n window.requestIdleCallback(window.main.restart);\n });",
"score": 15.323996329454628
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot import workspace',\n 'You must first configure the project folder before importing',\n ));\n return;\n }\n const targetFile = join(path, workspaceId + '.json');\n const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());\n await importWorkspaceData(dataRaw);\n // Force Insomnia to read all data",
"score": 15.160156906058845
},
{
"filename": "src/ui/projectDropdown/gitPullButton.ts",
"retrieved_chunk": " return;\n }\n const projectConfigDb = InternalDb.create();\n const projectConfig = projectConfigDb.getProject(projectId);\n const remote = projectConfig.remote ?? remotes[0].name;\n const pullResult = await gitClient.pull(remote, branch.current);\n await renderModal(alertModal(\n 'Pull succeded',\n `Pulled ${pullResult.files.length} changed files from ${remotes[0].name}/${branch.current}. Use \"Import Project\" to update the insomnia project`,\n ));",
"score": 14.255244544279343
},
{
"filename": "src/index.ts",
"retrieved_chunk": " },\n {\n label: 'Import workspace from Git',\n icon: 'upload',\n action: async () => {\n const projectId = getActiveProjectId();\n const workspaceId = getActiveWorkspace();\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {",
"score": 12.819761862687272
}
] | typescript | renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
)); |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string) | : Promise<ApiSpec | null> { |
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 28.832146691443867
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " const unitTestDb = new BaseDb<UnitTest>('UnitTest');\n for (const testSuite of data.unitTestSuites) {\n await unitTestSuitesDb.upsert(testSuite.testSuite);\n oldIds.removeTestSuites(testSuite.testSuite._id);\n for (const test of testSuite.tests) {\n await unitTestDb.upsert(test);\n oldIds.removeTest(test._id);\n }\n }\n await removeOldData(",
"score": 26.550782679113148
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 21.581231784606068
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 21.362654698689656
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " }\n }\n public getTests(): string[] {\n return this.tests;\n }\n public removeTest(id: string): void {\n const index = this.tests.indexOf(id);\n if (index !== -1) {\n this.tests.splice(index, 1);\n }",
"score": 13.856637317382221
}
] | typescript | : Promise<ApiSpec | null> { |
import fs from 'node:fs';
import { join } from 'path';
import InternalDb from './db/InternalDb';
import { getActiveProjectId } from './db/localStorageUtils';
import { exportProject } from './exportData';
import { importProject, readProjectData } from './importData';
import renderModal from './ui/react/renderModal';
import confirmModal from './ui/react/confirmModal';
let prevExport = '';
export default async function autoExport() {
const projectId = getActiveProjectId();
if (!projectId) {
return;
}
const config = InternalDb.create();
const { repositoryPath: path, autoExport } = config.getProject(projectId);
if (!path || !autoExport || projectId === 'proj_default-project') {
return;
}
const [projectData, workspaces] = await exportProject(projectId);
const newExportJson = JSON.stringify([projectData, workspaces]);
if (newExportJson === prevExport) {
// Nothing to export, so lets try to Import
await autoImportProject(path);
return;
}
prevExport = newExportJson;
const targetFile = join(path, 'project.json');
fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));
for (const workspace of workspaces) {
const targetFile = join(path, workspace.id + '.json');
fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));
}
}
let prevImport = '';
async function autoImportProject(path: string) {
let project, workspaceData;
try {
[project, workspaceData] = readProjectData(path);
} catch (e) {
console.error('[IPGI] Error while gathering import data during auto import. This might not be a bug', e);
return;
}
const newImportJson = JSON.stringify([project, workspaceData]);
// Do not import the first time
if (prevImport === '') {
prevImport = newImportJson;
return;
}
if (prevImport === newImportJson) {
// Nothing to import
return;
}
| const doImport = await renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
)); |
if (!doImport) {
return;
}
await importProject(project, workspaceData);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
}
| src/autoExport.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [project, workspaceData] = readProjectData(path);\n await importProject(project, workspaceData);\n // Force Insomnia to read all data again.\n // Wrapped with requestIdleCallback to make sure NeDB had enough time to save everything\n // @ts-ignore\n window.requestIdleCallback(window.main.restart);",
"score": 18.432040609905588
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot import workspace',\n 'You must first configure the project folder before importing',\n ));\n return;\n }\n const targetFile = join(path, workspaceId + '.json');\n const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());\n await importWorkspaceData(dataRaw);\n // Force Insomnia to read all data",
"score": 15.562655173005318
},
{
"filename": "src/ui/importNewProjectButton.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());\n workspaceData.push(workspace);\n }\n await importProject(project, workspaceData);\n // Force Insomnia to read all data again.\n // Wrapped with requestIdleCallback to make sure NeDB had enough time to save everything\n // @ts-ignore\n window.requestIdleCallback(window.main.restart);\n });",
"score": 15.323996329454628
},
{
"filename": "src/ui/projectDropdown/gitPullButton.ts",
"retrieved_chunk": " return;\n }\n const projectConfigDb = InternalDb.create();\n const projectConfig = projectConfigDb.getProject(projectId);\n const remote = projectConfig.remote ?? remotes[0].name;\n const pullResult = await gitClient.pull(remote, branch.current);\n await renderModal(alertModal(\n 'Pull succeded',\n `Pulled ${pullResult.files.length} changed files from ${remotes[0].name}/${branch.current}. Use \"Import Project\" to update the insomnia project`,\n ));",
"score": 14.612507437237035
},
{
"filename": "src/index.ts",
"retrieved_chunk": " },\n {\n label: 'Import workspace from Git',\n icon: 'upload',\n action: async () => {\n const projectId = getActiveProjectId();\n const workspaceId = getActiveWorkspace();\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {",
"score": 12.819761862687272
}
] | typescript | const doImport = await renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
)); |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
| async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> { |
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 37.665836420017804
},
{
"filename": "src/types.ts",
"retrieved_chunk": "}\nexport type GitSavedRequest = {\n type: 'request',\n id: string,\n request: BaseRequest,\n meta: RequestMeta,\n} | {\n type: 'group',\n id: string,\n group: RequestGroup,",
"score": 34.2621991150007
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " await requestGroupMetaDb.upsert(request.meta);\n oldIds.removeRequestGroupId(request.id);\n await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n continue;\n }\n await requestDb.upsert(request.request);\n await requestMetaDb.upsert(request.meta);\n oldIds.removeRequestId(request.id);\n }\n}",
"score": 30.206234114523976
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 24.17582785309761
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " for (const envId of oldIds.getEnvironmentIds()) {\n await environmentDb.deleteBy('_id', envId);\n }\n for (const requestId of oldIds.getRequestIds()) {\n await requestDb.deleteBy('_id', requestId);\n await requestMetaDb.deleteBy('parentId', requestId);\n }\n for (const requestGroupId of oldIds.getRequestGroupId()) {\n await requestGroupDb.deleteBy('_id', requestGroupId);\n await requestGroupMetaDb.deleteBy('parentId', requestGroupId);",
"score": 21.99254714013955
}
] | typescript | async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise< | [GitSavedProject, GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 34.835859014025296
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 27.843139693754495
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " url: string;\n name: string;\n description: string;\n method: string;\n body: RequestBody;\n parameters: RequestParameter[];\n headers: RequestHeader[];\n authentication: Record<string, string>; // This should be RequestAuthentication but is not used in the project\n metaSortKey: number;\n isPrivate: boolean;",
"score": 19.843282299223628
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " // - Workspace optionally has a parentId (which will be the id of a Project)\n parentId: string; // or null\n modified: number;\n created: number;\n isPrivate: boolean;\n name: string;\n}\n// Environment\nexport type Environment = {\n name: string;",
"score": 19.44767293339982
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 17.261577727028932
}
] | typescript | [GitSavedProject, GitSavedWorkspace[]]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject | , GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 34.835859014025296
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 27.843139693754495
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " url: string;\n name: string;\n description: string;\n method: string;\n body: RequestBody;\n parameters: RequestParameter[];\n headers: RequestHeader[];\n authentication: Record<string, string>; // This should be RequestAuthentication but is not used in the project\n metaSortKey: number;\n isPrivate: boolean;",
"score": 19.843282299223628
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " // - Workspace optionally has a parentId (which will be the id of a Project)\n parentId: string; // or null\n modified: number;\n created: number;\n isPrivate: boolean;\n name: string;\n}\n// Environment\nexport type Environment = {\n name: string;",
"score": 19.44767293339982
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 17.261577727028932
}
] | typescript | , GitSavedWorkspace[]]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
| ): Promise<GitSavedRequest[]> { |
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 65.94605452638957
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 56.490719605402305
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "async function removeOldData(\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n environmentDb: BaseDb<Environment>,\n testSuitesDb: BaseDb<UnittestSuite>,\n testDb: BaseDb<UnitTest>,\n) {",
"score": 55.097314632925624
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 26.995888333590933
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 23.145111423399115
}
] | typescript | ): Promise<GitSavedRequest[]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
| const meta: GitSavedWorkspaceMeta = { |
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 54.817536789742334
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // Collect OldIds of Requests / Folders so we can delete deleted Docs at the end\n const oldIds = await workspaceDb.findById(data.id)\n ? OldIds.fromOldData(await exportWorkspaceData(data.id))\n : OldIds.createEmpty();\n // Update Workspace metadata\n await workspaceDb.upsert(data.workspace);\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMeta: WorkspaceMeta = {\n ...data.meta,\n // These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here",
"score": 51.93854781470752
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);\n await importWorkspaceData(workspace);\n }\n // Delete old workspaces\n for (const oldWorkspace of oldWorkspaces) {\n await workspaceDb.deleteBy('_id', oldWorkspace);\n await workspaceMetaDb.deleteBy('parentId', oldWorkspace);\n }\n}\nasync function upsertRequestsRecursive(",
"score": 33.715455421615204
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 27.455720450372514
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(path, workspaceId + '.json');\n // TODO: Validate this using Zod\n const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());\n workspaceData.push(workspace);\n }",
"score": 25.41714918694944
}
] | typescript | const meta: GitSavedWorkspaceMeta = { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId | : string): Promise<[GitSavedProject, GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 34.835859014025296
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 27.843139693754495
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " url: string;\n name: string;\n description: string;\n method: string;\n body: RequestBody;\n parameters: RequestParameter[];\n headers: RequestHeader[];\n authentication: Record<string, string>; // This should be RequestAuthentication but is not used in the project\n metaSortKey: number;\n isPrivate: boolean;",
"score": 19.843282299223628
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " // - Workspace optionally has a parentId (which will be the id of a Project)\n parentId: string; // or null\n modified: number;\n created: number;\n isPrivate: boolean;\n name: string;\n}\n// Environment\nexport type Environment = {\n name: string;",
"score": 19.44767293339982
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 17.261577727028932
}
] | typescript | : string): Promise<[GitSavedProject, GitSavedWorkspace[]]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
| export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 34.835859014025296
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 27.843139693754495
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " url: string;\n name: string;\n description: string;\n method: string;\n body: RequestBody;\n parameters: RequestParameter[];\n headers: RequestHeader[];\n authentication: Record<string, string>; // This should be RequestAuthentication but is not used in the project\n metaSortKey: number;\n isPrivate: boolean;",
"score": 19.843282299223628
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " // - Workspace optionally has a parentId (which will be the id of a Project)\n parentId: string; // or null\n modified: number;\n created: number;\n isPrivate: boolean;\n name: string;\n}\n// Environment\nexport type Environment = {\n name: string;",
"score": 19.44767293339982
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 17.261577727028932
}
] | typescript | export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
| requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> { |
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 65.94605452638957
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 56.490719605402305
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "async function removeOldData(\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n environmentDb: BaseDb<Environment>,\n testSuitesDb: BaseDb<UnittestSuite>,\n testDb: BaseDb<UnitTest>,\n) {",
"score": 55.097314632925624
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 26.995888333590933
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 23.145111423399115
}
] | typescript | requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
| requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 61.36702140974455
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 50.48983955412122
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 31.2035518169889
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 30.190649481958612
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 18.332602854434324
}
] | typescript | requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
| requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 61.36702140974455
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 50.48983955412122
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 31.2035518169889
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 30.190649481958612
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 18.332602854434324
}
] | typescript | requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
| testDb: BaseDb<UnitTest>,
) { |
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 70.90993061007697
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 67.78292710079113
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 46.88845338816047
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 43.78184316231578
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 28.9311658060317
}
] | typescript | testDb: BaseDb<UnitTest>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: | BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 61.36702140974455
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 50.48983955412122
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 31.2035518169889
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 30.190649481958612
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 18.332602854434324
}
] | typescript | BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb | : BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 61.36702140974455
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 50.48983955412122
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 31.2035518169889
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 30.190649481958612
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 18.332602854434324
}
] | typescript | : BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
| environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 70.90993061007697
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 67.78292710079113
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 46.88845338816047
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 43.78184316231578
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 28.9311658060317
}
] | typescript | environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
import { exportProject, exportWorkspaceData } from './exportData';
import fs from 'node:fs';
import { importWorkspaceData } from './importData';
import InternalDb from './db/InternalDb';
import { getActiveProjectId, getActiveWorkspace } from './db/localStorageUtils';
import { join } from 'node:path';
import importNewProjectButton from './ui/importNewProjectButton';
import projectDropdown from './ui/projectDropdown';
import alertModal from './ui/react/alertModal';
import renderModal from './ui/react/renderModal';
import injectStyles from './ui/injectStyles';
import autoExport from './autoExport';
// Inject UI elements.
// @ts-ignore
const currentVersion = (window.gitIntegrationInjectCounter || 0) + 1;
// @ts-ignore
window.gitIntegrationInjectCounter = currentVersion;
function doInject() {
// @ts-ignore
// Check if the window was reloaded. When it was reloaded the Global counter changed
if (window.gitIntegrationInjectCounter !== currentVersion) {
return;
}
injectStyles();
projectDropdown();
importNewProjectButton();
window.requestAnimationFrame(doInject);
}
window.requestAnimationFrame(doInject);
setInterval(autoExport, 5000);
module.exports.workspaceActions = [
{
label: 'Export workspace to Git',
icon: 'download',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot export workspace',
'You must first configure the project folder before exporting',
));
return;
}
const data = await exportWorkspaceData(workspaceId);
const targetFile = join(path, workspaceId + '.json');
fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));
},
},
{
label: 'Import workspace from Git',
icon: 'upload',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot import workspace',
'You must first configure the project folder before importing',
));
return;
}
const targetFile = join(path, workspaceId + '.json');
const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());
| await importWorkspaceData(dataRaw); |
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
},
},
];
| src/index.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 63.07799320629084
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 61.54016130199804
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(path, workspaceId + '.json');\n // TODO: Validate this using Zod\n const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());\n workspaceData.push(workspace);\n }",
"score": 37.571091921232956
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n await gitClient.add(targetFile);\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n await gitClient.add(targetFile);\n }\n const status = await gitClient.status();\n if (status.staged.length === 0) {\n await renderModal(alertModal('No changes', 'There are no changes to commited'));",
"score": 34.45093228136452
},
{
"filename": "src/autoExport.ts",
"retrieved_chunk": " const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n }\n}\nlet prevImport = '';\nasync function autoImportProject(path: string) {\n let project, workspaceData;\n try {\n [project, workspaceData] = readProjectData(path);\n } catch (e) {",
"score": 33.48891006989954
}
] | typescript | await importWorkspaceData(dataRaw); |
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/pages/users/user.entity';
import { UserRepository } from 'src/pages/users/user.repository';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { UnauthorizedException } from "@nestjs/common/exceptions";
import * as bcrypt from 'bcryptjs';
import { AuthLoginDto } from './dto/auth-login.dto';
import { DefaultResponseDto } from './dto/default-response.dto';
import { EntityManager } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private jwtService: JwtService
) {}
async signUp(args:{
authCredentialDto: AuthCredentialDto,
queryRunner: EntityManager,
}) : Promise<DefaultResponseDto> {
try{
const IdCheck = await args.queryRunner.findOne(User,{
where:{ customId : args.authCredentialDto.customId }
});
if(IdCheck){
throw new UnauthorizedException('Id already exists');
}
const EmailCheck = await args.queryRunner.findOne(User,{
where:{ email : args.authCredentialDto.email }
});
if(EmailCheck){
throw new UnauthorizedException('Email already exists');
}
} catch (error) {
throw new UnauthorizedException(error.message);
}
const user = await this.userRepository.createUser(args.authCredentialDto);
return {statusCode:"200", contents : user};
}
async signIn(args:{
authLoginDto: | AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> { |
const {customId , password } = args.authLoginDto;
const user = await this.userRepository.findOne(
{where:{ customId : customId }}
);
if(user && await bcrypt.compare(password, user.password)){
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_SECRET_EXPIRATION_TIME,
});
const refreshToken = await this.jwtService.sign({id: user.id}, {
secret: process.env.JWT_REFRESH_TOKEN_SECRET,
expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRATION_TIME,
});
await this.setCurrentRefreshToken(refreshToken, user.id)
return {statusCode:"200", contents : {accessToken, refreshToken}};
}
else{
throw new UnauthorizedException('login failed');
}
}
async setCurrentRefreshToken(refreshToken: string, id: number) {
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
await this.userRepository.update(id, { refreshToken : hashedRefreshToken });
}
async getUserIfRefreshTokenMatches(refreshToken: string, id: number) {
const user = await this.userRepository.findOne({
where: { id },
});
if(user.refreshToken == null){
throw new UnauthorizedException('refresh token is null');
}
const isRefreshTokenMatching = await bcrypt.compare(
refreshToken,
user.refreshToken,
);
if (isRefreshTokenMatching) {
return user;
}else{
throw new UnauthorizedException('not matching refresh token');
}
}
async removeRefreshToken(id: number) {
return this.userRepository.update(id, {
refreshToken: null,
});
}
async getAccessToken(user:User) {
try{
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload);
return accessToken;
}catch(e){
throw new UnauthorizedException(e.message);
}
}
async signOut(user:User){
const userObject = await this.userRepository.findOne({
where: { customId : user.customId },
});
if(userObject){
await this.removeRefreshToken(userObject.id);
return {statusCode:"200", contents : "sign out success"};
}
else{
throw new UnauthorizedException('user not found');
}
}
}
| src/auth/auth.service.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 성공', type: DefaultResponseDto})\n @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n async signIn(\n @Body(ValidationPipe) authLoginDto: AuthLoginDto,\n @TransactionManager() queryRunnerManager: EntityManager,\n @Res({ passthrough: true }) response,\n ): Promise<DefaultResponseDto> {\n try{\n const result = await this.authService.signIn({\n authLoginDto,",
"score": 30.638163200363227
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n @UseGuards(AuthGuard('jwt-refresh-token'))\n async signInByRefreshToken(\n @TransactionManager() queryRunnerManager: EntityManager,\n @GetUser() user: User,\n ): Promise<DefaultResponseDto> {\n try{\n const accessToken = await this.authService.getAccessToken(user);\n return {\n statusCode: \"200\",",
"score": 21.424708535247
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": "export class UsersService {\n constructor(\n @InjectRepository(UserRepository)\n private userRepository: UserRepository\n ) { }\n async getAllUsers(): Promise<{ statusCode: string, contents: User[] }> {\n const userObj = await this.userRepository.find();\n return { statusCode: '200', contents: userObj };\n }\n async getUserInfo(user: User): Promise<{ statusCode: string, contents: User }> {",
"score": 20.007988134303655
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " authCredentialDto,\n queryRunner:queryRunnerManager,\n });\n return result;\n }catch(error){\n throw new HttpException(error.message, 401);\n }\n }\n @Post('/signin')\n @ApiOperation({summary: '로그인', description: '로그인 진행'})",
"score": 19.71153713401713
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }\n async updateDisconnectSocketId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n userObj.socketId = null;\n userObj.exitAt = new Date();\n await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }",
"score": 19.01500639094471
}
] | typescript | AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> { |
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/pages/users/user.entity';
import { UserRepository } from 'src/pages/users/user.repository';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { UnauthorizedException } from "@nestjs/common/exceptions";
import * as bcrypt from 'bcryptjs';
import { AuthLoginDto } from './dto/auth-login.dto';
import { DefaultResponseDto } from './dto/default-response.dto';
import { EntityManager } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private jwtService: JwtService
) {}
async signUp(args:{
authCredentialDto: AuthCredentialDto,
queryRunner: EntityManager,
}) : Promise<DefaultResponseDto> {
try{
const IdCheck = await args.queryRunner.findOne(User,{
where:{ customId : args.authCredentialDto.customId }
});
if(IdCheck){
throw new UnauthorizedException('Id already exists');
}
const EmailCheck = await args.queryRunner.findOne(User,{
where:{ email : args.authCredentialDto.email }
});
if(EmailCheck){
throw new UnauthorizedException('Email already exists');
}
} catch (error) {
throw new UnauthorizedException(error.message);
}
const user = await this.userRepository.createUser(args.authCredentialDto);
return {statusCode:"200", contents : user};
}
async signIn(args:{
| authLoginDto: AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> { |
const {customId , password } = args.authLoginDto;
const user = await this.userRepository.findOne(
{where:{ customId : customId }}
);
if(user && await bcrypt.compare(password, user.password)){
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_SECRET_EXPIRATION_TIME,
});
const refreshToken = await this.jwtService.sign({id: user.id}, {
secret: process.env.JWT_REFRESH_TOKEN_SECRET,
expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRATION_TIME,
});
await this.setCurrentRefreshToken(refreshToken, user.id)
return {statusCode:"200", contents : {accessToken, refreshToken}};
}
else{
throw new UnauthorizedException('login failed');
}
}
async setCurrentRefreshToken(refreshToken: string, id: number) {
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
await this.userRepository.update(id, { refreshToken : hashedRefreshToken });
}
async getUserIfRefreshTokenMatches(refreshToken: string, id: number) {
const user = await this.userRepository.findOne({
where: { id },
});
if(user.refreshToken == null){
throw new UnauthorizedException('refresh token is null');
}
const isRefreshTokenMatching = await bcrypt.compare(
refreshToken,
user.refreshToken,
);
if (isRefreshTokenMatching) {
return user;
}else{
throw new UnauthorizedException('not matching refresh token');
}
}
async removeRefreshToken(id: number) {
return this.userRepository.update(id, {
refreshToken: null,
});
}
async getAccessToken(user:User) {
try{
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload);
return accessToken;
}catch(e){
throw new UnauthorizedException(e.message);
}
}
async signOut(user:User){
const userObject = await this.userRepository.findOne({
where: { customId : user.customId },
});
if(userObject){
await this.removeRefreshToken(userObject.id);
return {statusCode:"200", contents : "sign out success"};
}
else{
throw new UnauthorizedException('user not found');
}
}
}
| src/auth/auth.service.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 성공', type: DefaultResponseDto})\n @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n async signIn(\n @Body(ValidationPipe) authLoginDto: AuthLoginDto,\n @TransactionManager() queryRunnerManager: EntityManager,\n @Res({ passthrough: true }) response,\n ): Promise<DefaultResponseDto> {\n try{\n const result = await this.authService.signIn({\n authLoginDto,",
"score": 30.638163200363227
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " authCredentialDto,\n queryRunner:queryRunnerManager,\n });\n return result;\n }catch(error){\n throw new HttpException(error.message, 401);\n }\n }\n @Post('/signin')\n @ApiOperation({summary: '로그인', description: '로그인 진행'})",
"score": 26.12555408221063
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " role: user.role,\n customId: user.customId,\n },\n };\n }catch(error){\n throw new HttpException(error.message, 500);\n }\n }\n}",
"score": 22.20468200093258
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " statusCode: \"200\",\n contents: \"로그아웃 성공\",\n };\n }catch(error){\n throw new HttpException(error.message, 500);\n }\n }\n @Get('/refresh')\n @ApiOperation({summary: 'Refresh Token 으로 AccessToken 발급', description: '헤더인경우 refresh_token, 쿠키인 경우 Refresh'})\n @ApiResponse({description: '로그인 성공', type: DefaultResponseDto})",
"score": 21.934190178019506
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n @UseGuards(AuthGuard('jwt-refresh-token'))\n async signInByRefreshToken(\n @TransactionManager() queryRunnerManager: EntityManager,\n @GetUser() user: User,\n ): Promise<DefaultResponseDto> {\n try{\n const accessToken = await this.authService.getAccessToken(user);\n return {\n statusCode: \"200\",",
"score": 21.424708535247
}
] | typescript | authLoginDto: AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> { |
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/pages/users/user.entity';
import { UserRepository } from 'src/pages/users/user.repository';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { UnauthorizedException } from "@nestjs/common/exceptions";
import * as bcrypt from 'bcryptjs';
import { AuthLoginDto } from './dto/auth-login.dto';
import { DefaultResponseDto } from './dto/default-response.dto';
import { EntityManager } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private jwtService: JwtService
) {}
async signUp(args:{
authCredentialDto: AuthCredentialDto,
queryRunner: EntityManager,
}) : Promise<DefaultResponseDto> {
try{
const IdCheck = await args.queryRunner.findOne(User,{
where:{ customId : args.authCredentialDto.customId }
});
if(IdCheck){
throw new UnauthorizedException('Id already exists');
}
const EmailCheck = await args.queryRunner.findOne(User,{
where:{ email : args.authCredentialDto.email }
});
if(EmailCheck){
throw new UnauthorizedException('Email already exists');
}
} catch (error) {
throw new UnauthorizedException(error.message);
}
const user = await this.userRepository.createUser(args.authCredentialDto);
return {statusCode:"200", contents : user};
}
async signIn(args:{
authLoginDto: AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> {
const {customId , | password } = args.authLoginDto; |
const user = await this.userRepository.findOne(
{where:{ customId : customId }}
);
if(user && await bcrypt.compare(password, user.password)){
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_SECRET_EXPIRATION_TIME,
});
const refreshToken = await this.jwtService.sign({id: user.id}, {
secret: process.env.JWT_REFRESH_TOKEN_SECRET,
expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRATION_TIME,
});
await this.setCurrentRefreshToken(refreshToken, user.id)
return {statusCode:"200", contents : {accessToken, refreshToken}};
}
else{
throw new UnauthorizedException('login failed');
}
}
async setCurrentRefreshToken(refreshToken: string, id: number) {
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
await this.userRepository.update(id, { refreshToken : hashedRefreshToken });
}
async getUserIfRefreshTokenMatches(refreshToken: string, id: number) {
const user = await this.userRepository.findOne({
where: { id },
});
if(user.refreshToken == null){
throw new UnauthorizedException('refresh token is null');
}
const isRefreshTokenMatching = await bcrypt.compare(
refreshToken,
user.refreshToken,
);
if (isRefreshTokenMatching) {
return user;
}else{
throw new UnauthorizedException('not matching refresh token');
}
}
async removeRefreshToken(id: number) {
return this.userRepository.update(id, {
refreshToken: null,
});
}
async getAccessToken(user:User) {
try{
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload);
return accessToken;
}catch(e){
throw new UnauthorizedException(e.message);
}
}
async signOut(user:User){
const userObject = await this.userRepository.findOne({
where: { customId : user.customId },
});
if(userObject){
await this.removeRefreshToken(userObject.id);
return {statusCode:"200", contents : "sign out success"};
}
else{
throw new UnauthorizedException('user not found');
}
}
}
| src/auth/auth.service.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 성공', type: DefaultResponseDto})\n @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n async signIn(\n @Body(ValidationPipe) authLoginDto: AuthLoginDto,\n @TransactionManager() queryRunnerManager: EntityManager,\n @Res({ passthrough: true }) response,\n ): Promise<DefaultResponseDto> {\n try{\n const result = await this.authService.signIn({\n authLoginDto,",
"score": 37.762102858067934
},
{
"filename": "src/pages/users/user.repository.ts",
"retrieved_chunk": " async createUser(authCredentialDto: AuthCredentialDto): Promise<User> {\n const { customId, name, email, password } = authCredentialDto;\n const salt = await bcrypt.genSalt();\n const hashedPassword = await bcrypt.hash(password, salt);\n const user = this.create({\n customId,\n name,\n email,\n password : hashedPassword\n })",
"score": 26.17188550748029
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n @UseGuards(AuthGuard('jwt-refresh-token'))\n async signInByRefreshToken(\n @TransactionManager() queryRunnerManager: EntityManager,\n @GetUser() user: User,\n ): Promise<DefaultResponseDto> {\n try{\n const accessToken = await this.authService.getAccessToken(user);\n return {\n statusCode: \"200\",",
"score": 22.037203755468855
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }\n async updateDisconnectSocketId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n userObj.socketId = null;\n userObj.exitAt = new Date();\n await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }",
"score": 20.91293009645221
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " async userSocketConnectionCheck(userId: number) {\n const userObj = await this.userRepository.findOne({ where: { id: userId } });\n if (userObj.socketId == null) {\n return;\n }\n return { statusCode: '200', contents: userObj };\n }\n async getUserByCustomId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n return { statusCode: '200', contents: userObj };",
"score": 20.817469793952764
}
] | typescript | password } = args.authLoginDto; |
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/pages/users/user.entity';
import { UserRepository } from 'src/pages/users/user.repository';
import { AuthCredentialDto } from './dto/auth-credential.dto';
import { UnauthorizedException } from "@nestjs/common/exceptions";
import * as bcrypt from 'bcryptjs';
import { AuthLoginDto } from './dto/auth-login.dto';
import { DefaultResponseDto } from './dto/default-response.dto';
import { EntityManager } from 'typeorm';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
private jwtService: JwtService
) {}
async signUp(args:{
authCredentialDto: AuthCredentialDto,
queryRunner: EntityManager,
}) : Promise<DefaultResponseDto> {
try{
const IdCheck = await args.queryRunner.findOne(User,{
where:{ customId : args.authCredentialDto.customId }
});
if(IdCheck){
throw new UnauthorizedException('Id already exists');
}
const EmailCheck = await args.queryRunner.findOne(User,{
where:{ email : args.authCredentialDto.email }
});
if(EmailCheck){
throw new UnauthorizedException('Email already exists');
}
} catch (error) {
throw new UnauthorizedException(error.message);
}
const user = await this.userRepository.createUser(args.authCredentialDto);
return {statusCode:"200", contents : user};
}
async signIn(args:{
authLoginDto: AuthLoginDto,
queryRunnerManager: EntityManager,
}) : Promise<DefaultResponseDto> {
| const {customId , password } = args.authLoginDto; |
const user = await this.userRepository.findOne(
{where:{ customId : customId }}
);
if(user && await bcrypt.compare(password, user.password)){
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
expiresIn: process.env.JWT_SECRET_EXPIRATION_TIME,
});
const refreshToken = await this.jwtService.sign({id: user.id}, {
secret: process.env.JWT_REFRESH_TOKEN_SECRET,
expiresIn: process.env.JWT_REFRESH_TOKEN_EXPIRATION_TIME,
});
await this.setCurrentRefreshToken(refreshToken, user.id)
return {statusCode:"200", contents : {accessToken, refreshToken}};
}
else{
throw new UnauthorizedException('login failed');
}
}
async setCurrentRefreshToken(refreshToken: string, id: number) {
const hashedRefreshToken = await bcrypt.hash(refreshToken, 10);
await this.userRepository.update(id, { refreshToken : hashedRefreshToken });
}
async getUserIfRefreshTokenMatches(refreshToken: string, id: number) {
const user = await this.userRepository.findOne({
where: { id },
});
if(user.refreshToken == null){
throw new UnauthorizedException('refresh token is null');
}
const isRefreshTokenMatching = await bcrypt.compare(
refreshToken,
user.refreshToken,
);
if (isRefreshTokenMatching) {
return user;
}else{
throw new UnauthorizedException('not matching refresh token');
}
}
async removeRefreshToken(id: number) {
return this.userRepository.update(id, {
refreshToken: null,
});
}
async getAccessToken(user:User) {
try{
const payload = { customId : user.customId };
const accessToken = await this.jwtService.sign(payload);
return accessToken;
}catch(e){
throw new UnauthorizedException(e.message);
}
}
async signOut(user:User){
const userObject = await this.userRepository.findOne({
where: { customId : user.customId },
});
if(userObject){
await this.removeRefreshToken(userObject.id);
return {statusCode:"200", contents : "sign out success"};
}
else{
throw new UnauthorizedException('user not found');
}
}
}
| src/auth/auth.service.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 성공', type: DefaultResponseDto})\n @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n async signIn(\n @Body(ValidationPipe) authLoginDto: AuthLoginDto,\n @TransactionManager() queryRunnerManager: EntityManager,\n @Res({ passthrough: true }) response,\n ): Promise<DefaultResponseDto> {\n try{\n const result = await this.authService.signIn({\n authLoginDto,",
"score": 37.762102858067934
},
{
"filename": "src/pages/users/user.repository.ts",
"retrieved_chunk": " async createUser(authCredentialDto: AuthCredentialDto): Promise<User> {\n const { customId, name, email, password } = authCredentialDto;\n const salt = await bcrypt.genSalt();\n const hashedPassword = await bcrypt.hash(password, salt);\n const user = this.create({\n customId,\n name,\n email,\n password : hashedPassword\n })",
"score": 26.17188550748029
},
{
"filename": "src/auth/auth.controller.ts",
"retrieved_chunk": " @ApiResponse({description: '로그인 실패', type: ErrorResponseDto , status: 401})\n @UseGuards(AuthGuard('jwt-refresh-token'))\n async signInByRefreshToken(\n @TransactionManager() queryRunnerManager: EntityManager,\n @GetUser() user: User,\n ): Promise<DefaultResponseDto> {\n try{\n const accessToken = await this.authService.getAccessToken(user);\n return {\n statusCode: \"200\",",
"score": 22.037203755468855
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }\n async updateDisconnectSocketId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n userObj.socketId = null;\n userObj.exitAt = new Date();\n await this.userRepository.save(userObj);\n return { statusCode: '200', contents: userObj };\n }",
"score": 21.794546974364295
},
{
"filename": "src/pages/users/users.service.ts",
"retrieved_chunk": " async userSocketConnectionCheck(userId: number) {\n const userObj = await this.userRepository.findOne({ where: { id: userId } });\n if (userObj.socketId == null) {\n return;\n }\n return { statusCode: '200', contents: userObj };\n }\n async getUserByCustomId(customId: string): Promise<{ statusCode: string, contents: User }> {\n const userObj = await this.userRepository.findOne({ where: { customId: customId } });\n return { statusCode: '200', contents: userObj };",
"score": 20.817469793952764
}
] | typescript | const {customId , password } = args.authLoginDto; |
import { CacheModule, MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
import { GatewayModule } from './socket-gateways/gateway.module';
import path from 'path';
import { resolve } from 'path';
import * as dotenv from 'dotenv';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { AuthTokenMiddleware } from './auth/authToken.middleware';
import { UsersModule } from './pages/users/users.module';
import { User } from './pages/users/user.entity';
import { SchedulerModule } from './pages/schedule/scheduler.module';
import { MatchModule } from './pages/match/match.module';
dotenv.config({ path: resolve(__dirname, '../.env') });
@Module({
imports: [
CacheModule.register(
{
isGlobal: true,
ttl: 60*60*12, // seconds
max: 1000, // maximum number of items in cache
},
),
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
TypeOrmModule.forRoot({
type: 'mariadb',
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT) as number,
username: process.env.DB_USER as string || 'abcd',
password: process.env.DB_PASS,
database: process.env.DB_DATABASE,
timezone: '+09:00',
entities: [User,],
synchronize: true,
}),
GatewayModule,
UsersModule,
AuthModule,
SchedulerModule,
MatchModule,
],
})
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply( | AuthTokenMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL }); |
}
}
| src/app.module.ts | jungsungwook-nestjs-core-game-ab8e09b | [
{
"filename": "src/main.ts",
"retrieved_chunk": "import { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { IoAdapter } from '@nestjs/platform-socket.io';\nimport * as dotenv from 'dotenv';\nimport * as path from 'path';\nimport { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';\ndotenv.config({ path: path.resolve(__dirname, '../.env') });\nasync function bootstrap() {\n const app = await NestFactory.create(AppModule);\n const options = new DocumentBuilder()",
"score": 13.457638334193058
},
{
"filename": "src/pages/schedule/scheduler.module.ts",
"retrieved_chunk": "})\nexport class SchedulerModule { }",
"score": 12.598966948818974
},
{
"filename": "src/pages/match/match.module.ts",
"retrieved_chunk": "export class MatchModule { }",
"score": 10.726401520072505
},
{
"filename": "src/socket-gateways/gateway.module.ts",
"retrieved_chunk": "import { MatchModule } from 'src/pages/match/match.module';\nimport { MatchGateway } from './match/gateway.match';\n@Module({\n imports:[\n UsersModule,\n AuthModule,\n BroadcastModule,\n Movement2dModule,\n RedisCacheModule,\n forwardRef(() => MatchModule),",
"score": 5.912902399895013
},
{
"filename": "src/auth/authToken.middleware.ts",
"retrieved_chunk": "import { Injectable, NestMiddleware } from '@nestjs/common'\nimport { InjectRepository } from '@nestjs/typeorm'\nimport { Request, Response } from 'express'\nimport * as jwt from 'jsonwebtoken'\nimport { User } from 'src/pages/users/user.entity'\n@Injectable()\nexport class AuthTokenMiddleware implements NestMiddleware {\n public async use(req: any, res: Response, next: () => void) {\n req.user = await this.verifyUser(req)\n return next()",
"score": 5.670815348597961
}
] | typescript | AuthTokenMiddleware)
.forRoutes({ path: '*', method: RequestMethod.ALL }); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
| ? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty(); |
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 57.21446838056329
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 46.05474258496512
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 44.44189640214712
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 34.032700327447984
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": "import { GitSavedRequest, GitSavedWorkspace } from './types';\nexport default class OldIds {\n private constructor(\n private environmentIds: string[],\n private requestIds: string[],\n private requestGroupIds: string[],\n private testSuites: string[],\n private tests: string[],\n ) {}\n public static createEmpty(): OldIds {",
"score": 25.02224373801363
}
] | typescript | ? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty(); |
import { exportProject, exportWorkspaceData } from './exportData';
import fs from 'node:fs';
import { importWorkspaceData } from './importData';
import InternalDb from './db/InternalDb';
import { getActiveProjectId, getActiveWorkspace } from './db/localStorageUtils';
import { join } from 'node:path';
import importNewProjectButton from './ui/importNewProjectButton';
import projectDropdown from './ui/projectDropdown';
import alertModal from './ui/react/alertModal';
import renderModal from './ui/react/renderModal';
import injectStyles from './ui/injectStyles';
import autoExport from './autoExport';
// Inject UI elements.
// @ts-ignore
const currentVersion = (window.gitIntegrationInjectCounter || 0) + 1;
// @ts-ignore
window.gitIntegrationInjectCounter = currentVersion;
function doInject() {
// @ts-ignore
// Check if the window was reloaded. When it was reloaded the Global counter changed
if (window.gitIntegrationInjectCounter !== currentVersion) {
return;
}
injectStyles();
projectDropdown();
importNewProjectButton();
window.requestAnimationFrame(doInject);
}
window.requestAnimationFrame(doInject);
setInterval(autoExport, 5000);
module.exports.workspaceActions = [
{
label: 'Export workspace to Git',
icon: 'download',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot export workspace',
'You must first configure the project folder before exporting',
));
return;
}
const data = | await exportWorkspaceData(workspaceId); |
const targetFile = join(path, workspaceId + '.json');
fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));
},
},
{
label: 'Import workspace from Git',
icon: 'upload',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot import workspace',
'You must first configure the project folder before importing',
));
return;
}
const targetFile = join(path, workspaceId + '.json');
const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());
await importWorkspaceData(dataRaw);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
},
},
];
| src/index.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 65.96736907392744
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 47.14054946625463
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " const projectId = getActiveProjectId();\n if (!projectId) {\n await renderModal(alertModal('Internal error', 'No ProjectId found in LocalStorage'));\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot import Project',",
"score": 41.926117942500746
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " // \"Close\" the dropdown\n projectDropdown.remove();\n const projectId = getActiveProjectId();\n if (!projectId) {\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(",
"score": 38.77693173540798
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [project, workspaceData] = readProjectData(path);\n await importProject(project, workspaceData);\n // Force Insomnia to read all data again.\n // Wrapped with requestIdleCallback to make sure NeDB had enough time to save everything\n // @ts-ignore\n window.requestIdleCallback(window.main.restart);",
"score": 35.48436936128083
}
] | typescript | await exportWorkspaceData(workspaceId); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
| export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> { |
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 35.037510472152974
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 30.807710806013525
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 27.291264517998965
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 27.107780557457513
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " });\n }\n const groups = await requestGroupDb.findBy('parentId', parentId);\n for (const group of groups) {\n const metas = await requestGroupMetaDb.findBy('parentId', group._id);\n // Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3\n const meta = metas[0] || createDefaultFolderMeta(group._id);\n gitSavedRequests.push({\n type: 'group',\n id: group._id,",
"score": 26.65284240015371
}
] | typescript | export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb | .findById(projectId); |
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 48.35181600628512
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 23.83720797962611
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 22.920287293218564
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " }\n for (const testSuites of oldIds.getTestSuites()) {\n await testSuitesDb.deleteBy('_id', testSuites);\n }\n for (const test of oldIds.getTests()) {\n await testDb.deleteBy('_id', test);\n }\n}\nexport async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {\n const workspaceDb = new BaseDb<Workspace>('Workspace');",
"score": 19.82017945767946
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " const projectId = getActiveProjectId();\n if (!projectId) {\n await renderModal(alertModal('Internal error', 'No ProjectId found in LocalStorage'));\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot import Project',",
"score": 18.82295704351193
}
] | typescript | .findById(projectId); |
import fs from 'node:fs';
import { join } from 'path';
import InternalDb from './db/InternalDb';
import { getActiveProjectId } from './db/localStorageUtils';
import { exportProject } from './exportData';
import { importProject, readProjectData } from './importData';
import renderModal from './ui/react/renderModal';
import confirmModal from './ui/react/confirmModal';
let prevExport = '';
export default async function autoExport() {
const projectId = getActiveProjectId();
if (!projectId) {
return;
}
const config = InternalDb.create();
const { repositoryPath: path, autoExport } = config.getProject(projectId);
if (!path || !autoExport || projectId === 'proj_default-project') {
return;
}
const [projectData, workspaces] = await exportProject(projectId);
const newExportJson = JSON.stringify([projectData, workspaces]);
if (newExportJson === prevExport) {
// Nothing to export, so lets try to Import
await autoImportProject(path);
return;
}
prevExport = newExportJson;
const targetFile = join(path, 'project.json');
fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));
for (const workspace of workspaces) {
const targetFile = join(path, workspace.id + '.json');
fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));
}
}
let prevImport = '';
async function autoImportProject(path: string) {
let project, workspaceData;
try {
| [project, workspaceData] = readProjectData(path); |
} catch (e) {
console.error('[IPGI] Error while gathering import data during auto import. This might not be a bug', e);
return;
}
const newImportJson = JSON.stringify([project, workspaceData]);
// Do not import the first time
if (prevImport === '') {
prevImport = newImportJson;
return;
}
if (prevImport === newImportJson) {
// Nothing to import
return;
}
const doImport = await renderModal<boolean>(confirmModal(
'Import project',
'Import chhanged project data? Insomnia will restart.',
));
if (!doImport) {
return;
}
await importProject(project, workspaceData);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
}
| src/autoExport.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 58.44266761868209
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n await gitClient.add(targetFile);\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n await gitClient.add(targetFile);\n }\n const status = await gitClient.status();\n if (status.staged.length === 0) {\n await renderModal(alertModal('No changes', 'There are no changes to commited'));",
"score": 55.07795613672701
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot export workspace',\n 'You must first configure the project folder before exporting',\n ));\n return;\n }\n const data = await exportWorkspaceData(workspaceId);\n const targetFile = join(path, workspaceId + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));\n },",
"score": 44.89709858485208
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(path, workspaceId + '.json');\n // TODO: Validate this using Zod\n const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());\n workspaceData.push(workspace);\n }",
"score": 40.100030413252334
},
{
"filename": "src/index.ts",
"retrieved_chunk": " await renderModal(alertModal(\n 'Cannot import workspace',\n 'You must first configure the project folder before importing',\n ));\n return;\n }\n const targetFile = join(path, workspaceId + '.json');\n const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());\n await importWorkspaceData(dataRaw);\n // Force Insomnia to read all data",
"score": 32.10921768180792
}
] | typescript | [project, workspaceData] = readProjectData(path); |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, | GitSavedWorkspace[]]> { |
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 34.835859014025296
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 27.843139693754495
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " url: string;\n name: string;\n description: string;\n method: string;\n body: RequestBody;\n parameters: RequestParameter[];\n headers: RequestHeader[];\n authentication: Record<string, string>; // This should be RequestAuthentication but is not used in the project\n metaSortKey: number;\n isPrivate: boolean;",
"score": 19.843282299223628
},
{
"filename": "src/insomniaDbTypes.ts",
"retrieved_chunk": " // - Workspace optionally has a parentId (which will be the id of a Project)\n parentId: string; // or null\n modified: number;\n created: number;\n isPrivate: boolean;\n name: string;\n}\n// Environment\nexport type Environment = {\n name: string;",
"score": 19.44767293339982
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 17.261577727028932
}
] | typescript | GitSavedWorkspace[]]> { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
| testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 70.90993061007697
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 67.78292710079113
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 46.88845338816047
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 43.78184316231578
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 28.9311658060317
}
] | typescript | testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function | getApiSpec(workspaceId: string): Promise<ApiSpec | null> { |
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 28.832146691443867
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " const unitTestDb = new BaseDb<UnitTest>('UnitTest');\n for (const testSuite of data.unitTestSuites) {\n await unitTestSuitesDb.upsert(testSuite.testSuite);\n oldIds.removeTestSuites(testSuite.testSuite._id);\n for (const test of testSuite.tests) {\n await unitTestDb.upsert(test);\n oldIds.removeTest(test._id);\n }\n }\n await removeOldData(",
"score": 26.550782679113148
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 21.581231784606068
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 21.362654698689656
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " }\n }\n public getTests(): string[] {\n return this.tests;\n }\n public removeTest(id: string): void {\n const index = this.tests.indexOf(id);\n if (index !== -1) {\n this.tests.splice(index, 1);\n }",
"score": 13.856637317382221
}
] | typescript | getApiSpec(workspaceId: string): Promise<ApiSpec | null> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
| requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> { |
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 65.94605452638957
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 56.490719605402305
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "async function removeOldData(\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n environmentDb: BaseDb<Environment>,\n testSuitesDb: BaseDb<UnittestSuite>,\n testDb: BaseDb<UnitTest>,\n) {",
"score": 55.097314632925624
},
{
"filename": "src/importData.ts",
"retrieved_chunk": "import { join } from 'node:path';\nimport fs from 'node:fs';\nimport BaseDb from './db/BaseDb';\nimport { exportWorkspaceData } from './exportData';\nimport { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport OldIds from './OldIds';\nimport { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';\nexport function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {\n // Read the Project file\n const projectFile = join(path, 'project.json');",
"score": 26.995888333590933
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 23.145111423399115
}
] | typescript | requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> { |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaces = await workspaceDb.findBy('parentId', fullProject._id);
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
| const unittestDb = new BaseDb<UnitTest>('UnitTest'); |
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": "async function removeOldData(\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n environmentDb: BaseDb<Environment>,\n testSuitesDb: BaseDb<UnittestSuite>,\n testDb: BaseDb<UnitTest>,\n) {",
"score": 40.551725953744295
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " sidebarHidden: false,\n sidebarWidth: 19,\n pushSnapshotOnInitialize: false,\n };\n await workspaceMetaDb.upsert(fullMeta);\n const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);",
"score": 36.54683321546272
},
{
"filename": "src/types.ts",
"retrieved_chunk": " workspace: Workspace,\n meta: GitSavedWorkspaceMeta,\n requests: GitSavedRequest[],\n environments: Environment[],\n apiSpec?: ApiSpec,\n unitTestSuites: GitSavedUnitTestSuite[],\n}\nexport type GitSavedUnitTestSuite = {\n testSuite: UnittestSuite,\n tests: UnitTest[],",
"score": 32.08938949134308
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " requests: GitSavedRequest[],\n oldIds: OldIds,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n) {\n for (const request of requests) {\n if (request.type === 'group') {\n await requestGroupDb.upsert(request.group);",
"score": 32.08099124254285
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " const environmentDb = new BaseDb<Environment>('Environment');\n for (const environment of data.environments) {\n await environmentDb.upsert(environment);\n oldIds.removeEnvironmentId(environment._id);\n }\n if (data.apiSpec) {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n await apiSpecDb.upsert(data.apiSpec);\n }\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 30.940487765581082
}
] | typescript | const unittestDb = new BaseDb<UnitTest>('UnitTest'); |
import BaseDb from './db/BaseDb';
import { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';
import { randomBytes } from 'crypto';
function createDefaultFolderMeta(parentId: string): RequestGroupMeta {
return {
collapsed: true,
parentId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestGroupMeta',
_id: 'fldm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
};
}
function createDefaultRequestMeta(parentId: string): RequestMeta {
return {
parentId,
previewMode: "friendly", // PREVIEW_MODE_FRIENDLY
responseFilter: '',
responseFilterHistory: [],
activeResponseId: null,
savedRequestBody: {},
pinned: false,
lastActive: 0,
downloadPath: null,
expandedAccordionKeys: {},
created: Date.now(),
isPrivate: false,
modified: Date.now(),
type: 'RequestMeta',
_id: 'reqm_' + randomBytes(16).toString('hex'),
name: '', // This is not used by insomnia.
}
}
export async function exportProject(projectId: string): Promise<[GitSavedProject, GitSavedWorkspace[]]> {
// Load the Project
const projectDb = new BaseDb<Project>('Project');
const fullProject = await projectDb.findById(projectId);
if (!fullProject) {
throw new Error('Project not found with id ' + projectId);
}
const project: GitSavedProject = {
id: fullProject._id,
name: fullProject.name,
remoteId: fullProject.remoteId,
workspaceIds: [],
};
// Load all workspaces
const workspaceDb = new BaseDb<Workspace>('Workspace');
| const workspaces = await workspaceDb.findBy('parentId', fullProject._id); |
const savedWorkspaces: GitSavedWorkspace[] = [];
for (const workspace of workspaces) {
savedWorkspaces.push(await exportWorkspaceData(workspace._id));
project.workspaceIds.push(workspace._id);
}
return [project, savedWorkspaces];
}
// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests
async function getRequestsForParentId(
parentId: string,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
): Promise<GitSavedRequest[]> {
const gitSavedRequests: GitSavedRequest[] = [];
const requests = await requestDb.findBy('parentId', parentId);
for (const request of requests) {
const metas = await requestMetaDb.findBy('parentId', request._id);
// When duplicating a Workspace the Request meta is not automaticly created
// As a workaround we use the default object.
// See: https://github.com/Kong/insomnia/blob/develop/packages/insomnia/src/models/request-meta.ts#L32
const meta = metas[0] || createDefaultRequestMeta(request._id);
gitSavedRequests.push({
type: 'request',
id: request._id,
meta,
request,
});
}
const groups = await requestGroupDb.findBy('parentId', parentId);
for (const group of groups) {
const metas = await requestGroupMetaDb.findBy('parentId', group._id);
// Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3
const meta = metas[0] || createDefaultFolderMeta(group._id);
gitSavedRequests.push({
type: 'group',
id: group._id,
group,
children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),
meta,
});
}
return gitSavedRequests;
}
async function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {
const savedUnittestSuites: GitSavedUnitTestSuite[] = [];
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unittestDb = new BaseDb<UnitTest>('UnitTest');
const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);
for (const testSuite of unitTestSuites) {
const tests = await unittestDb.findBy('parentId', testSuite._id);
savedUnittestSuites.push({
tests,
testSuite,
});
}
return savedUnittestSuites;
}
async function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);
return apiSpecs[0] ?? null;
}
export async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {
// Find workspace
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspace = await workspaceDb.findById(workspaceId);
if (!workspace) {
throw new Error('No Workspace found for id: ' + workspaceId);
}
const name = workspace.name;
// Find WorkspaceMeta
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);
const fullMeta = fullMetas[0];
const meta: GitSavedWorkspaceMeta = {
_id: fullMeta._id,
created: fullMeta.created,
isPrivate: fullMeta.isPrivate,
modified: fullMeta.modified,
name: fullMeta.name,
parentId: fullMeta.parentId,
type: fullMeta.type,
activeActivity: fullMeta.activeActivity,
activeEnvironmentId: fullMeta.activeEnvironmentId,
activeRequestId: fullMeta.activeRequestId,
};
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
// Find environments
const environmentDb = new BaseDb<Environment>('Environment');
const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);
if (baseEnvironments.length === 0) {
throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);
}
const baseEnvironment = baseEnvironments[0];
// Get all SubEnv -> Filter out private ones -> Add the BaseEnv to the Top
const environments = (await environmentDb.findBy('parentId', baseEnvironment._id))
.filter((env) => env.isPrivate === false);
environments.unshift(baseEnvironment);
const apiSpec = await getApiSpec(workspaceId);
const unitTestSuites = await getTestSuites(workspaceId);
return {
id: workspaceId,
name,
workspace,
meta,
requests,
environments,
apiSpec,
unitTestSuites,
};
}
| src/exportData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/importData.ts",
"retrieved_chunk": " isPrivate: false,\n modified: Date.now(),\n parentId: null,\n type: 'Project',\n });\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');\n let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);\n // Update all Workspaces\n for (const workspace of workspaces) {",
"score": 50.416138508542566
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " return [project, workspaceData];\n}\nexport async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {\n // Upsert the Project\n const projectDb = new BaseDb<Project>('Project');\n await projectDb.upsert({\n _id: project.id,\n name: project.name,\n remoteId: project.remoteId,\n created: Date.now(),",
"score": 41.212829283200094
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " }\n for (const testSuites of oldIds.getTestSuites()) {\n await testSuitesDb.deleteBy('_id', testSuites);\n }\n for (const test of oldIds.getTests()) {\n await testDb.deleteBy('_id', test);\n }\n}\nexport async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {\n const workspaceDb = new BaseDb<Workspace>('Workspace');",
"score": 29.74373493424668
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BaseRequest, WorkspaceMeta, RequestGroup, RequestGroupMeta, RequestMeta, Workspace, Environment, BaseModel, UnittestSuite, UnitTest, ApiSpec } from './insomniaDbTypes';\nexport type GitSavedProject = {\n name: string,\n id: string,\n remoteId: string | null,\n workspaceIds: string[],\n}\nexport type GitSavedWorkspace = {\n name: string,\n id: string,",
"score": 28.863647227429336
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);\n await importWorkspaceData(workspace);\n }\n // Delete old workspaces\n for (const oldWorkspace of oldWorkspaces) {\n await workspaceDb.deleteBy('_id', oldWorkspace);\n await workspaceMetaDb.deleteBy('parentId', oldWorkspace);\n }\n}\nasync function upsertRequestsRecursive(",
"score": 26.50150994373445
}
] | typescript | const workspaces = await workspaceDb.findBy('parentId', fullProject._id); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let | oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id); |
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 45.1801702770687
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 43.64727997719855
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " if (!workspace) {\n throw new Error('No Workspace found for id: ' + workspaceId);\n }\n const name = workspace.name;\n // Find WorkspaceMeta\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);\n const fullMeta = fullMetas[0];\n const meta: GitSavedWorkspaceMeta = {\n _id: fullMeta._id,",
"score": 43.143773848333105
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 42.02918351922835
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " responseFilter: '',\n responseFilterHistory: [],\n activeResponseId: null,\n savedRequestBody: {},\n pinned: false,\n lastActive: 0,\n downloadPath: null,\n expandedAccordionKeys: {},\n created: Date.now(),\n isPrivate: false,",
"score": 33.474989460085474
}
] | typescript | oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
| requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 61.36702140974455
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 50.48983955412122
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 31.2035518169889
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 30.190649481958612
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 18.332602854434324
}
] | typescript | requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb. | deleteBy('_id', oldWorkspace); |
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 57.399599270373216
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 32.92795598626259
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " if (!workspace) {\n throw new Error('No Workspace found for id: ' + workspaceId);\n }\n const name = workspace.name;\n // Find WorkspaceMeta\n const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');\n const fullMetas = await workspaceMetaDb.findBy('parentId', workspaceId);\n const fullMeta = fullMetas[0];\n const meta: GitSavedWorkspaceMeta = {\n _id: fullMeta._id,",
"score": 31.448270059583045
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n await gitClient.add(targetFile);\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n await gitClient.add(targetFile);\n }\n const status = await gitClient.status();\n if (status.staged.length === 0) {\n await renderModal(alertModal('No changes', 'There are no changes to commited'));",
"score": 30.785636474987076
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " });\n }\n const groups = await requestGroupDb.findBy('parentId', parentId);\n for (const group of groups) {\n const metas = await requestGroupMetaDb.findBy('parentId', group._id);\n // Create default GroupMetadata when nothing was found. Not sure when this happens but should fix #3\n const meta = metas[0] || createDefaultFolderMeta(group._id);\n gitSavedRequests.push({\n type: 'group',\n id: group._id,",
"score": 29.678454297642833
}
] | typescript | deleteBy('_id', oldWorkspace); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element | .querySelectorAll(BLOCKS.join(", ")); |
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "};\n/**\n * Return the scrollable parent element of the given element\n *\n * @param node {HTMLElement} Element to start searching\n * @returns {HTMLElement | null} Scrollable parent element\n */\nconst getScrollParent = (node: HTMLElement): HTMLElement | null => {\n\tif (node == null) return null;\n\tif (node.scrollHeight > node.clientHeight) {",
"score": 19.42661469120886
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\tscrollable?.scrollBy({\n\t\tbehavior: \"auto\",\n\t\ttop: rect.top - 200,\n\t});\n};\n/**\n * Find next block element to select.\n * Return null if there is no next block element.\n *\n * @param currentElement {HTMLElement} Current element to start searching",
"score": 17.86388617063111
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\t\tparent = parent.parentElement;\n\t}\n\t// If no block element found, return null\n\treturn null;\n};\n/**\n * Find previous block element to select.\n * Return null if there is no previous block element.\n *\n * @param currentElement {HTMLElement} Current element to start searching",
"score": 17.65686592797294
},
{
"filename": "src/constants.ts",
"retrieved_chunk": " * Class name for block selector\n */\nexport const BLOCK_SELECTOR = \"rve-block-selector\";\n/**\n * Attribute name for block elements\n */\nexport const BLOCK_ATTR = \"data-rve-block\";\n/**\n * Class name for selected block\n */",
"score": 17.439356706147763
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is collapsed\n */\nconst isCollapsed = (element: HTMLElement) => {\n\treturn element.hasClass(IS_COLLAPSED);\n};\n/**\n * Find first block element inside the given element\n *",
"score": 15.619814374573583
}
] | typescript | .querySelectorAll(BLOCKS.join(", ")); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb | : BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 61.36702140974455
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 50.48983955412122
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 31.2035518169889
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 30.190649481958612
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 18.332602854434324
}
] | typescript | : BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) {
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
return element.hasClass(IS_COLLAPSED);
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
| return element.getAttribute(BLOCK_ATTR) === "true"; |
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t * @returns {boolean} True if container is initialized\n\t */\n\tprivate isContainerNotInitialized(container: HTMLElement) {\n\t\treturn (\n\t\t\tcontainer instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)\n\t\t);\n\t}\n\t/**",
"score": 35.95359985998941
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set `data-rve-block` attribute to block elements.\n\t *\n\t * @param element {HTMLElement} Element to start searching\n\t */\n\tprivate elementsToBlocks(element: HTMLElement) {\n\t\tconst elements = element.querySelectorAll(BLOCKS.join(\", \"));\n\t\telements.forEach((el) => {\n\t\t\tif (el.hasClass(FRONTMATTER)) return;",
"score": 32.96531312461412
},
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "export const selectTopBlockInTheView: RveCommand = (\n\tplugin: ReadingViewEnhancer\n) => ({\n\tid: \"select-top-block-in-the-view\",\n\tname: \"Select Top Block in the View\",\n\tcheckCallback: (checking: boolean): boolean => {\n\t\t// If checking is set to true, perform a preliminary check.\n\t\tif (checking) {\n\t\t\tif (isNotReadingView(plugin)) return false;\n\t\t\telse if (isNotEnabled(plugin)) return false;",
"score": 28.114447099184485
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 26.69631660086385
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t\t}\n\t\t// @ts-ignore\n\t\tconst container = context?.containerEl;\n\t\tif (this.isContainerNotInitialized(container)) {\n\t\t\tthis.initializeContainer(container);\n\t\t}\n\t\tthis.elementsToBlocks(element);\n\t}\n\t/**\n\t * Check if container is initialized.",
"score": 25.44561428882835
}
] | typescript | return element.getAttribute(BLOCK_ATTR) === "true"; |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: | BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 61.36702140974455
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 50.48983955412122
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 31.2035518169889
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 30.190649481958612
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 18.332602854434324
}
] | typescript | BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) { |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
| el.setAttribute(BLOCK_ATTR, "true"); |
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/constants.ts",
"retrieved_chunk": " * Class name for block selector\n */\nexport const BLOCK_SELECTOR = \"rve-block-selector\";\n/**\n * Attribute name for block elements\n */\nexport const BLOCK_ATTR = \"data-rve-block\";\n/**\n * Class name for selected block\n */",
"score": 24.058566593500707
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\telse return null;\n};\n/**\n * Check if the given element is a block element\n *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is a block element\n */\nconst isBlock = (element: HTMLElement) => {\n\treturn element.getAttribute(BLOCK_ATTR) === \"true\";",
"score": 21.5890631032493
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "};\n/**\n * Return the scrollable parent element of the given element\n *\n * @param node {HTMLElement} Element to start searching\n * @returns {HTMLElement | null} Scrollable parent element\n */\nconst getScrollParent = (node: HTMLElement): HTMLElement | null => {\n\tif (node == null) return null;\n\tif (node.scrollHeight > node.clientHeight) {",
"score": 21.482773366273516
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is collapsed\n */\nconst isCollapsed = (element: HTMLElement) => {\n\treturn element.hasClass(IS_COLLAPSED);\n};\n/**\n * Find first block element inside the given element\n *",
"score": 21.186961134727156
},
{
"filename": "src/constants.ts",
"retrieved_chunk": "/**\n * Class name for the preview view\n */\nexport const MARKDOWN_PREVIEW_VIEW = \"markdown-preview-view\";\n/**\n * Class name for the frontmatter element\n */\nexport const FRONTMATTER = \"frontmatter\";\n/**\n * List of selectors for block elements",
"score": 20.085627843127654
}
] | typescript | el.setAttribute(BLOCK_ATTR, "true"); |
import { Plugin } from "obsidian";
import RveStyles, { BlockColorRule } from "./styles";
import { RveSettingTab, RveSettings, DEFAULT_SETTINGS } from "./settings";
import Commands from "./commands";
import BlockSelector from "./block-selector";
export default class ReadingViewEnhancer extends Plugin {
settings: RveSettings;
styles: RveStyles;
blockSelector: BlockSelector;
/**
* On load,
*
* - Load settings & styles
* - Activate block selector
* - It actually do its work if settings.enableBlockSelector is true
* - Register all commands
* - Add settings tab
*/
async onload() {
// Settings & Styles
await this.loadSettings();
this.styles = new RveStyles();
this.app.workspace.onLayoutReady(() => this.applySettingsToStyles());
// Activate block selector.
this.blockSelector = new BlockSelector(this);
this.blockSelector.activate();
// Register commands
new Commands(this).register();
// Add settings tab at last
this.addSettingTab(new RveSettingTab(this));
// Leave a message in the console
console.log("Loaded 'Reading View Enhancer'");
}
/**
* On unload,
*
* - Remove all styles
*/
async onunload() {
this.styles.cleanup();
// Leave a message in the console
console.log("Unloaded 'Reading View Enhancer'");
}
// ===================================================================
/**
* Load settings
*/
async loadSettings() {
| this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); |
}
/**
* Save settings
*/
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Apply settings to styles
*
* - Apply block color
* - Apply always on collapse indicator
* - Apply prevent table overflowing
* - Apply scrollable code
*/
private applySettingsToStyles() {
this.applyBlockColor();
this.applyAlwaysOnCollapse();
this.applyPreventTableOverflowing();
this.applyScrollableCode();
this.styles.apply();
}
/**
* Apply block color
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyBlockColor(isImmediate = false) {
const blockColor = this.styles.of("block-color") as BlockColorRule;
blockColor.set(this.settings.blockColor);
if (isImmediate) this.styles.apply();
}
/**
* Apply always on collapse indicator
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyAlwaysOnCollapse(isImmediate = false) {
this.styles.of("collapse-indicator").isActive =
this.settings.alwaysOnCollapseIndicator;
if (isImmediate) this.styles.apply();
}
/**
* Apply prevent table overflowing
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyPreventTableOverflowing(isImmediate = false) {
this.styles.of("prevent-table-overflowing").isActive =
this.settings.preventTableOverflowing;
if (isImmediate) this.styles.apply();
}
/**
* Apply scrollable code
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyScrollableCode(isImmediate = false) {
this.styles.of("scrollable-code").isActive = this.settings.scrollableCode;
if (isImmediate) this.styles.apply();
}
}
| src/main.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/settings/index.ts",
"retrieved_chunk": "\t\tcontainerEl.empty();\n\t\t// Add header\n\t\tcontainerEl.createEl(\"h1\", { text: \"Reading View Enhancer\" });\n\t\t// Add block selector settings\n\t\tnew BlockSelectorSettings(containerEl, this.plugin);\n\t\t// Add miscellaneous settings\n\t\tnew MiscellaneousSettings(containerEl, this.plugin);\n\t}\n}",
"score": 17.85268676426329
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\tcleanup() {\n\t\tthis.styleTag.remove();\n\t}\n\t/**\n\t * Get a rule by key\n\t *\n\t * @param rule {RuleKey} rule's key\n\t * @returns {StyleRule} One of the rules\n\t */\n\tof(rule: RuleKey) {",
"score": 9.011902127145929
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t * Also, creates a button to set color to the current accent color.\n\t *\n\t * @param color {ColorComponent} Color component\n\t */\n\tcolorPicker(color: ColorComponent) {\n\t\tconst { settings } = this.plugin;\n\t\tcolor.setValue(settings.blockColor).onChange((changed) => {\n\t\t\t// save on change\n\t\t\tsettings.blockColor = toHex(changed);\n\t\t\tthis.plugin.saveSettings();",
"score": 8.978530323463879
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Activate BlockSelector\n\t */\n\tactivate() {\n\t\tthis.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));\n\t}\n\t/**\n\t * Select top block in the view\n\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */",
"score": 8.577645733752624
},
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "export const selectTopBlockInTheView: RveCommand = (\n\tplugin: ReadingViewEnhancer\n) => ({\n\tid: \"select-top-block-in-the-view\",\n\tname: \"Select Top Block in the View\",\n\tcheckCallback: (checking: boolean): boolean => {\n\t\t// If checking is set to true, perform a preliminary check.\n\t\tif (checking) {\n\t\t\tif (isNotReadingView(plugin)) return false;\n\t\t\telse if (isNotEnabled(plugin)) return false;",
"score": 8.071312751462674
}
] | typescript | this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); |
import { Plugin } from "obsidian";
import RveStyles, { BlockColorRule } from "./styles";
import { RveSettingTab, RveSettings, DEFAULT_SETTINGS } from "./settings";
import Commands from "./commands";
import BlockSelector from "./block-selector";
export default class ReadingViewEnhancer extends Plugin {
settings: RveSettings;
styles: RveStyles;
blockSelector: BlockSelector;
/**
* On load,
*
* - Load settings & styles
* - Activate block selector
* - It actually do its work if settings.enableBlockSelector is true
* - Register all commands
* - Add settings tab
*/
async onload() {
// Settings & Styles
await this.loadSettings();
this.styles = new RveStyles();
this.app.workspace.onLayoutReady(() => this.applySettingsToStyles());
// Activate block selector.
this.blockSelector = new BlockSelector(this);
this.blockSelector.activate();
// Register commands
new Commands(this).register();
// Add settings tab at last
this.addSettingTab(new RveSettingTab(this));
// Leave a message in the console
console.log("Loaded 'Reading View Enhancer'");
}
/**
* On unload,
*
* - Remove all styles
*/
async onunload() {
this.styles.cleanup();
// Leave a message in the console
console.log("Unloaded 'Reading View Enhancer'");
}
// ===================================================================
/**
* Load settings
*/
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
/**
* Save settings
*/
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Apply settings to styles
*
* - Apply block color
* - Apply always on collapse indicator
* - Apply prevent table overflowing
* - Apply scrollable code
*/
private applySettingsToStyles() {
this.applyBlockColor();
this.applyAlwaysOnCollapse();
this.applyPreventTableOverflowing();
this.applyScrollableCode();
this.styles.apply();
}
/**
* Apply block color
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyBlockColor(isImmediate = false) {
| const blockColor = this.styles.of("block-color") as BlockColorRule; |
blockColor.set(this.settings.blockColor);
if (isImmediate) this.styles.apply();
}
/**
* Apply always on collapse indicator
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyAlwaysOnCollapse(isImmediate = false) {
this.styles.of("collapse-indicator").isActive =
this.settings.alwaysOnCollapseIndicator;
if (isImmediate) this.styles.apply();
}
/**
* Apply prevent table overflowing
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyPreventTableOverflowing(isImmediate = false) {
this.styles.of("prevent-table-overflowing").isActive =
this.settings.preventTableOverflowing;
if (isImmediate) this.styles.apply();
}
/**
* Apply scrollable code
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyScrollableCode(isImmediate = false) {
this.styles.of("scrollable-code").isActive = this.settings.scrollableCode;
if (isImmediate) this.styles.apply();
}
}
| src/main.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/settings/index.ts",
"retrieved_chunk": "\tscrollableCode: boolean;\n}\nexport const DEFAULT_SETTINGS: RveSettings = {\n\tblockColor: \"#8b6cef\", // Obsidian default color\n\tenableBlockSelector: false,\n\tdisableBlockSelectorOnMobile: false,\n\talwaysOnCollapseIndicator: false,\n\tpreventTableOverflowing: false,\n\tscrollableCode: false,\n};",
"score": 16.777308901066665
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\treturn this.rules[rule];\n\t}\n\t/**\n\t * Apply all active rules\n\t */\n\tapply() {\n\t\tconst style = Object.values(this.rules)\n\t\t\t.filter((rule) => rule.isActive)\n\t\t\t.map((rule) => rule.getRule())\n\t\t\t.join(\"\\n\");",
"score": 15.252882142291709
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t */\n\taccentColorButton(button: ButtonComponent, color: ColorComponent) {\n\t\tbutton.setButtonText(\"Use current accent color\").onClick(() => {\n\t\t\tconst accentColor = this.getAccentColor();\n\t\t\tcolor.setValue(accentColor);\n\t\t\tthis.plugin.settings.blockColor = accentColor;\n\t\t\tthis.plugin.saveSettings();\n\t\t\tthis.plugin.applyBlockColor(true);\n\t\t});\n\t}",
"score": 13.789860261638353
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set the block color\n\t *\n\t * @param blockColor {string} The block color\n\t */\n\tset(blockColor: string) {\n\t\tthis.blockColor = blockColor;\n\t}\n}",
"score": 13.293383757372384
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t * Also, creates a button to set color to the current accent color.\n\t *\n\t * @param color {ColorComponent} Color component\n\t */\n\tcolorPicker(color: ColorComponent) {\n\t\tconst { settings } = this.plugin;\n\t\tcolor.setValue(settings.blockColor).onChange((changed) => {\n\t\t\t// save on change\n\t\t\tsettings.blockColor = toHex(changed);\n\t\t\tthis.plugin.saveSettings();",
"score": 13.197831500145547
}
] | typescript | const blockColor = this.styles.of("block-color") as BlockColorRule; |
import { BLOCK_ATTR, COLLAPSE_INDICATORS, SELECTED_BLOCK } from "../constants";
import {
findNextBlock,
findPreviousBlock,
isBottomInView,
isTopInView,
scrollBottomIntoView,
scrollTopIntoView,
} from "./selection-util";
/**
* Handle block selection.
* This class is used by BlockSelector.
*/
export default class SelectionHandler {
selectedBlock: HTMLElement | null;
constructor() {
this.selectedBlock = null;
}
/**
* Select block element
*
* @param block {HTMLElement} Block element
*/
select(block: HTMLElement) {
block.focus();
block.addClass(SELECTED_BLOCK);
this.selectedBlock = block;
}
/**
* Unselect block element.
* If there is no selected block, do nothing.
*
* @param block {HTMLElement} Block element
*/
unselect() {
if (this.selectedBlock) {
this.selectedBlock.removeClass(SELECTED_BLOCK);
this.selectedBlock.blur();
this.selectedBlock = null;
}
}
/**
* Trigger 'select' on clicked block element.
*
* @param e {MouseEvent} Mouse event
*/
onBlockClick(e: MouseEvent) {
const target = e.target as HTMLElement;
| const block = target.closest(`[${BLOCK_ATTR}=true]`); |
if (block instanceof HTMLElement) {
this.select(block);
}
}
/**
* On keydown, navigate between blocks or fold/unfold blocks.
*
* - `ArrowDown`: Select next block
* - `ArrowUp`: Select previous block
* - `ArrowLeft` & `ArrowRight`: Fold/Unfold block
*
* If selected block is too long,
* `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.
* This is for loading adjacent blocks which are not in the DOM tree.
*
* @param e {KeyboardEvent} Keyboard event
* @param scrollable {HTMLElement} Scrollable parent element
*/
onKeyDown(e: KeyboardEvent) {
const block = e.target as HTMLElement;
if (e.key === "ArrowDown") {
e.preventDefault();
this.selectNextBlockOrScroll(block);
} else if (e.key === "ArrowUp") {
e.preventDefault();
this.selectPreviousBlockOrScroll(block);
} else if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
e.preventDefault();
this.toggleFold(block);
} else if (e.key === "Escape") {
this.unselect();
}
}
/**
* Select next block or scroll to see the block's bottom.
*
* @param block {HTMLElement} Block element
*/
private selectNextBlockOrScroll(block: HTMLElement) {
if (!isBottomInView(block)) {
scrollBottomIntoView(block);
} else {
const next = findNextBlock(block);
if (next) this.select(next as HTMLElement);
}
}
/**
* Select previous block or scroll to see the block's top.
*
* @param block {HTMLElement} Block element
*/
private selectPreviousBlockOrScroll(block: HTMLElement) {
if (!isTopInView(block)) {
scrollTopIntoView(block);
} else {
const prev = findPreviousBlock(block);
if (prev) this.select(prev as HTMLElement);
}
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
const blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);
// If there is no block, do nothing
if (blocks.length === 0) return;
// Get the index of the topmost block in the view
let topIndex = -1;
for (let i = 0; i < blocks.length; i++) {
topIndex = i;
const rect = blocks[i].getBoundingClientRect();
if (rect.bottom > 120) {
break;
}
}
const topBlock = blocks[topIndex];
this.select(topBlock as HTMLElement);
}
/**
* Fold/Unfold block.
*
* @param block {HTMLElement} Block element
*/
private toggleFold(block: HTMLElement) {
const collapseIndicator = block.querySelector(
COLLAPSE_INDICATORS.join(",")
) as HTMLElement;
if (collapseIndicator) {
collapseIndicator.click();
}
}
}
| src/block-selector/selection-handler.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t\t\tthis.selectionHandler.onBlockClick(e)\n\t\t);\n\t\t// On focusout, unselect block element\n\t\tcontainer.addEventListener(\"focusout\", () =>\n\t\t\tthis.selectionHandler.unselect()\n\t\t);\n\t\t// On keydown, navigate between blocks or fold/unfold blocks\n\t\tcontainer.addEventListener(\"keydown\", (e) =>\n\t\t\tthis.selectionHandler.onKeyDown(e)\n\t\t);",
"score": 23.637912254228304
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t * Initialize container.\n\t * Add some event listeners to container.\n\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t */\n\tprivate initializeContainer(container: HTMLElement) {\n\t\t// Mark container as initialized\n\t\tcontainer.addClass(BLOCK_SELECTOR);\n\t\t// On click, select block element\n\t\tcontainer.addEventListener(\"click\", (e) =>",
"score": 22.810755601921688
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\telse return null;\n};\n/**\n * Check if the given element is a block element\n *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is a block element\n */\nconst isBlock = (element: HTMLElement) => {\n\treturn element.getAttribute(BLOCK_ATTR) === \"true\";",
"score": 10.645179333626754
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " */\nconst findLastBlock = (element: HTMLElement): HTMLElement | null => {\n\tif (isCollapsed(element) && isBlock(element)) return element;\n\tlet block = null;\n\tconst childElements = element.children;\n\tfor (let i = childElements.length - 1; i >= 0; i--) {\n\t\tblock = findLastBlock(childElements[i] as HTMLElement);\n\t\tif (block) return block;\n\t}\n\tif (isBlock(element)) return element;",
"score": 7.740932365806246
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\t\tblock = findBlock(childElements[i] as HTMLElement);\n\t\tif (block) return block;\n\t}\n\treturn null;\n};\n/**\n * Find last block element inside the given element\n *\n * @param element {HTMLElement} Element to search\n * @returns {HTMLElement | null} Last block element",
"score": 7.5762649907096105
}
] | typescript | const block = target.closest(`[${BLOCK_ATTR}=true]`); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
| if (el.hasClass(FRONTMATTER)) return; |
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "};\n/**\n * Return the scrollable parent element of the given element\n *\n * @param node {HTMLElement} Element to start searching\n * @returns {HTMLElement | null} Scrollable parent element\n */\nconst getScrollParent = (node: HTMLElement): HTMLElement | null => {\n\tif (node == null) return null;\n\tif (node.scrollHeight > node.clientHeight) {",
"score": 21.482773366273516
},
{
"filename": "src/constants.ts",
"retrieved_chunk": " * Class name for block selector\n */\nexport const BLOCK_SELECTOR = \"rve-block-selector\";\n/**\n * Attribute name for block elements\n */\nexport const BLOCK_ATTR = \"data-rve-block\";\n/**\n * Class name for selected block\n */",
"score": 21.25934535554995
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is collapsed\n */\nconst isCollapsed = (element: HTMLElement) => {\n\treturn element.hasClass(IS_COLLAPSED);\n};\n/**\n * Find first block element inside the given element\n *",
"score": 21.186961134727156
},
{
"filename": "src/constants.ts",
"retrieved_chunk": "/**\n * Class name for the preview view\n */\nexport const MARKDOWN_PREVIEW_VIEW = \"markdown-preview-view\";\n/**\n * Class name for the frontmatter element\n */\nexport const FRONTMATTER = \"frontmatter\";\n/**\n * List of selectors for block elements",
"score": 20.085627843127654
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\t\tparent = parent.parentElement;\n\t}\n\t// If no block element found, return null\n\treturn null;\n};\n/**\n * Find previous block element to select.\n * Return null if there is no previous block element.\n *\n * @param currentElement {HTMLElement} Current element to start searching",
"score": 19.930622057632306
}
] | typescript | if (el.hasClass(FRONTMATTER)) return; |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
| container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
); |
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "\t\t\telse if (isMobileAndDisabled(plugin)) return false;\n\t\t\telse return true;\n\t\t}\n\t\t// If checking is set to false, perform an action.\n\t\telse {\n\t\t\tconst container = getReadingViewContainer(plugin);\n\t\t\tif (container) {\n\t\t\t\tplugin.blockSelector.selectTopBlockInTheView(container);\n\t\t\t}\n\t\t\treturn true;",
"score": 44.32787067689049
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 25.496823648419305
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is collapsed\n */\nconst isCollapsed = (element: HTMLElement) => {\n\treturn element.hasClass(IS_COLLAPSED);\n};\n/**\n * Find first block element inside the given element\n *",
"score": 23.201143260129108
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\telse return null;\n};\n/**\n * Check if the given element is a block element\n *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is a block element\n */\nconst isBlock = (element: HTMLElement) => {\n\treturn element.getAttribute(BLOCK_ATTR) === \"true\";",
"score": 23.1410680837299
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\t\t\tif (prevBlock) return prevBlock;\n\t\t\tparentSibling = parentSibling.previousElementSibling;\n\t\t}\n\t\tparent = parent.parentElement;\n\t}\n\t// If no block element found, return null\n\treturn null;\n};\n/**\n * Check if the given element is collapsed",
"score": 12.990476199495244
}
] | typescript | container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
); |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
while (parent && | !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) { |
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
return element.hasClass(IS_COLLAPSED);
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
return element.getAttribute(BLOCK_ATTR) === "true";
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 17.219546169555386
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 16.323907291499104
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t} else {\n\t\t\tconst next = findNextBlock(block);\n\t\t\tif (next) this.select(next as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select previous block or scroll to see the block's top.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */",
"score": 12.536528209157257
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t * @returns {boolean} True if container is initialized\n\t */\n\tprivate isContainerNotInitialized(container: HTMLElement) {\n\t\treturn (\n\t\t\tcontainer instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)\n\t\t);\n\t}\n\t/**",
"score": 10.479018833816914
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set `data-rve-block` attribute to block elements.\n\t *\n\t * @param element {HTMLElement} Element to start searching\n\t */\n\tprivate elementsToBlocks(element: HTMLElement) {\n\t\tconst elements = element.querySelectorAll(BLOCKS.join(\", \"));\n\t\telements.forEach((el) => {\n\t\t\tif (el.hasClass(FRONTMATTER)) return;",
"score": 10.458206333608763
}
] | typescript | !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) { |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) {
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
| return element.hasClass(IS_COLLAPSED); |
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
return element.getAttribute(BLOCK_ATTR) === "true";
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t * @returns {boolean} True if container is initialized\n\t */\n\tprivate isContainerNotInitialized(container: HTMLElement) {\n\t\treturn (\n\t\t\tcontainer instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)\n\t\t);\n\t}\n\t/**",
"score": 36.68406781265187
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set `data-rve-block` attribute to block elements.\n\t *\n\t * @param element {HTMLElement} Element to start searching\n\t */\n\tprivate elementsToBlocks(element: HTMLElement) {\n\t\tconst elements = element.querySelectorAll(BLOCKS.join(\", \"));\n\t\telements.forEach((el) => {\n\t\t\tif (el.hasClass(FRONTMATTER)) return;",
"score": 30.950180722839406
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t\t}\n\t\t// @ts-ignore\n\t\tconst container = context?.containerEl;\n\t\tif (this.isContainerNotInitialized(container)) {\n\t\t\tthis.initializeContainer(container);\n\t\t}\n\t\tthis.elementsToBlocks(element);\n\t}\n\t/**\n\t * Check if container is initialized.",
"score": 22.077453641141016
},
{
"filename": "src/constants.ts",
"retrieved_chunk": "export const SELECTED_BLOCK = \"rve-selected-block\";\n/**\n * Selector for collapse indicators\n */\nexport const COLLAPSE_INDICATORS = [\".collapse-indicator\", \".callout-fold\"];\n/**\n * Class name for collapsed block\n */\nexport const IS_COLLAPSED = \"is-collapsed\";",
"score": 21.43455162671556
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 21.301930036551262
}
] | typescript | return element.hasClass(IS_COLLAPSED); |
import { PluginSettingTab } from "obsidian";
import ReadingViewEnhancer from "../main";
import BlockSelectorSettings from "./block";
import MiscellaneousSettings from "./miscellaneous";
export interface RveSettings {
blockColor: string;
enableBlockSelector: boolean;
disableBlockSelectorOnMobile: boolean;
alwaysOnCollapseIndicator: boolean;
preventTableOverflowing: boolean;
scrollableCode: boolean;
}
export const DEFAULT_SETTINGS: RveSettings = {
blockColor: "#8b6cef", // Obsidian default color
enableBlockSelector: false,
disableBlockSelectorOnMobile: false,
alwaysOnCollapseIndicator: false,
preventTableOverflowing: false,
scrollableCode: false,
};
// ===================================================================
/**
* Settings tab.
* In this tab, you can change settings.
*
* - Block color
* - Enable/Disable Block Selector
*/
export class RveSettingTab extends PluginSettingTab {
plugin: ReadingViewEnhancer;
constructor(plugin: ReadingViewEnhancer) {
super(app, plugin);
this.plugin = plugin;
}
/**
* Displays settings tab.
*/
display() {
const { containerEl } = this;
// Clear all first
containerEl.empty();
// Add header
containerEl.createEl("h1", { text: "Reading View Enhancer" });
// Add block selector settings
new | BlockSelectorSettings(containerEl, this.plugin); |
// Add miscellaneous settings
new MiscellaneousSettings(containerEl, this.plugin);
}
}
| src/settings/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport BlockColorSetting from \"./block-color\";\nimport EnableBlockSelectorSetting from \"./block-selector\";\nimport DisableBlockSelectorOnMobileSetting from \"./block-selector-mobile\";\n/**\n * Registers settings components related to block selector.\n */\nexport default class BlockSelectorSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Block Selector\" });",
"score": 24.50338424858236
},
{
"filename": "src/settings/miscellaneous/index.ts",
"retrieved_chunk": "\t\tnew BlockColorSetting(containerEl, plugin);\n\t\tnew EnableBlockSelectorSetting(containerEl, plugin);\n\t\tnew DisableBlockSelectorOnMobileSetting(containerEl, plugin);\n\t}\n}",
"score": 22.78354606304834
},
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "\t\tnew AlwaysOnCollapseIndicatorSetting(containerEl, plugin);\n\t\tnew PreventTableOverflowingSetting(containerEl, plugin);\n\t\tnew ScrollableCodeSetting(containerEl, plugin);\n\t}\n}",
"score": 22.78354606304834
},
{
"filename": "src/settings/miscellaneous/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport AlwaysOnCollapseIndicatorSetting from \"./always-on-collapse-indicator\";\nimport PreventTableOverflowingSetting from \"./prevent-table-overflow\";\nimport ScrollableCodeSetting from \"./scrollable-code\";\n/**\n * Registers settings components not related to block.\n */\nexport default class MiscellaneousSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Miscellaneous\" });",
"score": 17.375545898270115
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t// Leave a message in the console\n\t\tconsole.log(\"Loaded 'Reading View Enhancer'\");\n\t}\n\t/**\n\t * On unload,\n\t *\n\t * - Remove all styles\n\t */\n\tasync onunload() {\n\t\tthis.styles.cleanup();",
"score": 14.850797328351144
}
] | typescript | BlockSelectorSettings(containerEl, this.plugin); |
import { PluginSettingTab } from "obsidian";
import ReadingViewEnhancer from "../main";
import BlockSelectorSettings from "./block";
import MiscellaneousSettings from "./miscellaneous";
export interface RveSettings {
blockColor: string;
enableBlockSelector: boolean;
disableBlockSelectorOnMobile: boolean;
alwaysOnCollapseIndicator: boolean;
preventTableOverflowing: boolean;
scrollableCode: boolean;
}
export const DEFAULT_SETTINGS: RveSettings = {
blockColor: "#8b6cef", // Obsidian default color
enableBlockSelector: false,
disableBlockSelectorOnMobile: false,
alwaysOnCollapseIndicator: false,
preventTableOverflowing: false,
scrollableCode: false,
};
// ===================================================================
/**
* Settings tab.
* In this tab, you can change settings.
*
* - Block color
* - Enable/Disable Block Selector
*/
export class RveSettingTab extends PluginSettingTab {
plugin: ReadingViewEnhancer;
constructor(plugin: ReadingViewEnhancer) {
super(app, plugin);
this.plugin = plugin;
}
/**
* Displays settings tab.
*/
display() {
const { containerEl } = this;
// Clear all first
containerEl.empty();
// Add header
containerEl.createEl("h1", { text: "Reading View Enhancer" });
// Add block selector settings
new BlockSelectorSettings(containerEl, this.plugin);
// Add miscellaneous settings
| new MiscellaneousSettings(containerEl, this.plugin); |
}
}
| src/settings/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/settings/miscellaneous/index.ts",
"retrieved_chunk": "\t\tnew BlockColorSetting(containerEl, plugin);\n\t\tnew EnableBlockSelectorSetting(containerEl, plugin);\n\t\tnew DisableBlockSelectorOnMobileSetting(containerEl, plugin);\n\t}\n}",
"score": 33.860399178605604
},
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "\t\tnew AlwaysOnCollapseIndicatorSetting(containerEl, plugin);\n\t\tnew PreventTableOverflowingSetting(containerEl, plugin);\n\t\tnew ScrollableCodeSetting(containerEl, plugin);\n\t}\n}",
"score": 33.860399178605604
},
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport BlockColorSetting from \"./block-color\";\nimport EnableBlockSelectorSetting from \"./block-selector\";\nimport DisableBlockSelectorOnMobileSetting from \"./block-selector-mobile\";\n/**\n * Registers settings components related to block selector.\n */\nexport default class BlockSelectorSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Block Selector\" });",
"score": 28.697961796811406
},
{
"filename": "src/settings/miscellaneous/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport AlwaysOnCollapseIndicatorSetting from \"./always-on-collapse-indicator\";\nimport PreventTableOverflowingSetting from \"./prevent-table-overflow\";\nimport ScrollableCodeSetting from \"./scrollable-code\";\n/**\n * Registers settings components not related to block.\n */\nexport default class MiscellaneousSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Miscellaneous\" });",
"score": 25.026030234085503
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tawait this.loadSettings();\n\t\tthis.styles = new RveStyles();\n\t\tthis.app.workspace.onLayoutReady(() => this.applySettingsToStyles());\n\t\t// Activate block selector.\n\t\tthis.blockSelector = new BlockSelector(this);\n\t\tthis.blockSelector.activate();\n\t\t// Register commands\n\t\tnew Commands(this).register();\n\t\t// Add settings tab at last\n\t\tthis.addSettingTab(new RveSettingTab(this));",
"score": 24.10089454656611
}
] | typescript | new MiscellaneousSettings(containerEl, this.plugin); |
import { SELECTED_BLOCK } from "./constants";
/**
* Style rule that holds the template
* and the function to inject variables
*/
class StyleRule {
private template: string;
private injectVariables: (template: string) => string;
isActive: boolean;
constructor(template: string, injectVariables: (template: string) => string) {
this.template = template;
this.isActive = false;
this.injectVariables = injectVariables;
}
/**
* Get the rule after injecting variables
*
* @returns {string} The rule
*/
getRule() {
return this.injectVariables(this.template);
}
}
/**
* Block color rule.
*
* Accepts a block color and injects it into the template.
*/
export class BlockColorRule extends StyleRule {
private blockColor: string;
constructor() {
const template = `
| .${SELECTED_BLOCK} { |
position: relative;
}
.${SELECTED_BLOCK}::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
background-color: {{BLOCK_COLOR}}1a;
}
`;
super(template, (template: string) => {
return template.replace("{{BLOCK_COLOR}}", this.blockColor);
});
this.isActive = true;
}
/**
* Set the block color
*
* @param blockColor {string} The block color
*/
set(blockColor: string) {
this.blockColor = blockColor;
}
}
/**
* Collapse indicator rule.
*
* No variables to inject.
*/
export class CollapseIndicatorRule extends StyleRule {
constructor() {
const template = `
.markdown-preview-section .collapse-indicator {
opacity: 1;
}
`;
super(template, (template: string) => template);
}
}
/**
* Prevent table overflowing rule.
*
* No variables to inject.
*/
export class PreventTableOverflowingRule extends StyleRule {
constructor() {
const template = `
.markdown-preview-section > div:has(table) {
overflow: auto;
}
.markdown-preview-section thead > tr > th,
.markdown-preview-section tbody > tr > td {
white-space: nowrap;
}
`;
super(template, (template: string) => template);
}
}
/**
* Scrollable code rule.
*
* No variables to inject.
*/
export class ScrollableCodeRule extends StyleRule {
constructor() {
const template = `
.markdown-preview-section div > pre {
overflow: hidden;
white-space: pre-wrap;
}
.markdown-preview-section div > pre > code {
display: block;
overflow: auto;
white-space: pre;
}
`;
super(template, (template: string) => template);
}
}
type RuleKey =
| "block-color"
| "collapse-indicator"
| "prevent-table-overflowing"
| "scrollable-code";
/**
* The class that manages all style rules.
*/
export default class RveStyles {
styleTag: HTMLStyleElement;
rules: Record<RuleKey, StyleRule>;
constructor() {
this.styleTag = document.createElement("style");
this.styleTag.id = "rve-styles";
document.getElementsByTagName("head")[0].appendChild(this.styleTag);
this.rules = {
"block-color": new BlockColorRule(),
"collapse-indicator": new CollapseIndicatorRule(),
"prevent-table-overflowing": new PreventTableOverflowingRule(),
"scrollable-code": new ScrollableCodeRule(),
};
}
/**
* Clean up the style tag
*/
cleanup() {
this.styleTag.remove();
}
/**
* Get a rule by key
*
* @param rule {RuleKey} rule's key
* @returns {StyleRule} One of the rules
*/
of(rule: RuleKey) {
return this.rules[rule];
}
/**
* Apply all active rules
*/
apply() {
const style = Object.values(this.rules)
.filter((rule) => rule.isActive)
.map((rule) => rule.getRule())
.join("\n");
this.styleTag.innerHTML = style;
}
}
| src/styles.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/main.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Apply block color\n\t *\n\t * @param isImmediate {boolean} Whether to apply styles immediately\n\t */\n\tapplyBlockColor(isImmediate = false) {\n\t\tconst blockColor = this.styles.of(\"block-color\") as BlockColorRule;\n\t\tblockColor.set(this.settings.blockColor);\n\t\tif (isImmediate) this.styles.apply();",
"score": 15.266327204609393
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": " * You can select a block by clicking on it and then use arrow keys to navigate between blocks.\n * For selected block, the background color will be changed.\n * You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.\n * Foldable blocks are having `collapse-indicator` or `callout-fold` class.\n */\nexport default class BlockSelector {\n\tplugin: ReadingViewEnhancer;\n\tselectionHandler: SelectionHandler;\n\tselectedBlock: HTMLElement | null;\n\t/**",
"score": 14.416271054912105
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t * Also, creates a button to set color to the current accent color.\n\t *\n\t * @param color {ColorComponent} Color component\n\t */\n\tcolorPicker(color: ColorComponent) {\n\t\tconst { settings } = this.plugin;\n\t\tcolor.setValue(settings.blockColor).onChange((changed) => {\n\t\t\t// save on change\n\t\t\tsettings.blockColor = toHex(changed);\n\t\t\tthis.plugin.saveSettings();",
"score": 14.173814580315499
},
{
"filename": "src/settings/index.ts",
"retrieved_chunk": "// ===================================================================\n/**\n * Settings tab.\n * In this tab, you can change settings.\n *\n * - Block color\n * - Enable/Disable Block Selector\n */\nexport class RveSettingTab extends PluginSettingTab {\n\tplugin: ReadingViewEnhancer;",
"score": 13.38432989875228
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t/**\n\t * Gets current accent color from Obsidian.\n\t *\n\t * @returns Current accent color in hex format\n\t */\n\tprivate getAccentColor(): string {\n\t\tconst workspaceEl = this.plugin.app.workspace.containerEl;\n\t\tconst accentColor = toHex(\n\t\t\tgetComputedStyle(workspaceEl).getPropertyValue(\"--color-accent\").trim()\n\t\t);",
"score": 12.924385917011891
}
] | typescript | .${SELECTED_BLOCK} { |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
| this.selectionHandler.selectTopBlockInTheView(viewContainer); |
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 36.692632063448784
},
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "\t\t\t}\n\t\t});\n\t},\n});\n/**\n * Select top block in the view\n *\n * @param plugin {ReadingViewEnhancer} Plugin instance\n * @returns {RveCommand} Select top block in the view command\n */",
"score": 18.639144795782308
},
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "export const selectTopBlockInTheView: RveCommand = (\n\tplugin: ReadingViewEnhancer\n) => ({\n\tid: \"select-top-block-in-the-view\",\n\tname: \"Select Top Block in the View\",\n\tcheckCallback: (checking: boolean): boolean => {\n\t\t// If checking is set to true, perform a preliminary check.\n\t\tif (checking) {\n\t\t\tif (isNotReadingView(plugin)) return false;\n\t\t\telse if (isNotEnabled(plugin)) return false;",
"score": 17.913755557082528
},
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "\t\t\telse if (isMobileAndDisabled(plugin)) return false;\n\t\t\telse return true;\n\t\t}\n\t\t// If checking is set to false, perform an action.\n\t\telse {\n\t\t\tconst container = getReadingViewContainer(plugin);\n\t\t\tif (container) {\n\t\t\t\tplugin.blockSelector.selectTopBlockInTheView(container);\n\t\t\t}\n\t\t\treturn true;",
"score": 13.639336035733308
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\tprivate selectPreviousBlockOrScroll(block: HTMLElement) {\n\t\tif (!isTopInView(block)) {\n\t\t\tscrollTopIntoView(block);\n\t\t} else {\n\t\t\tconst prev = findPreviousBlock(block);\n\t\t\tif (prev) this.select(prev as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select top block in the view",
"score": 13.483263340005323
}
] | typescript | this.selectionHandler.selectTopBlockInTheView(viewContainer); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb | : BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const requestDb = new BaseDb<BaseRequest>('Request');\n const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');\n const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');\n const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');\n const requests = await getRequestsForParentId(workspaceId, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);\n // Find environments\n const environmentDb = new BaseDb<Environment>('Environment');\n const baseEnvironments = await environmentDb.findBy('parentId', workspaceId);\n if (baseEnvironments.length === 0) {\n throw new Error('No BaseEnvironment found for parentId: ' + workspaceId);",
"score": 70.90993061007697
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "async function getRequestsForParentId(\n parentId: string,\n requestDb: BaseDb<BaseRequest>,\n requestMetaDb: BaseDb<RequestMeta>,\n requestGroupDb: BaseDb<RequestGroup>,\n requestGroupMetaDb: BaseDb<RequestGroupMeta>,\n): Promise<GitSavedRequest[]> {\n const gitSavedRequests: GitSavedRequest[] = [];\n const requests = await requestDb.findBy('parentId', parentId);\n for (const request of requests) {",
"score": 64.49473796829479
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "import BaseDb from './db/BaseDb';\nimport { BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Workspace, WorkspaceMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';\nimport { GitSavedProject, GitSavedRequest, GitSavedUnitTestSuite, GitSavedWorkspace, GitSavedWorkspaceMeta } from './types';\nimport { randomBytes } from 'crypto';\nfunction createDefaultFolderMeta(parentId: string): RequestGroupMeta {\n return {\n collapsed: true,\n parentId,\n created: Date.now(),\n isPrivate: false,",
"score": 45.658619073662464
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " group,\n children: await getRequestsForParentId(group._id, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb),\n meta,\n });\n }\n return gitSavedRequests;\n}\nasync function getTestSuites(workspaceId: string): Promise<GitSavedUnitTestSuite[]> {\n const savedUnittestSuites: GitSavedUnitTestSuite[] = [];\n const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');",
"score": 40.249834138142496
},
{
"filename": "src/db/BaseDb.ts",
"retrieved_chunk": "import Nedb from 'nedb';\nimport fsPath from 'node:path';\nimport { BaseModel } from '../insomniaDbTypes';\ntype DbTargets = 'Request' | 'RequestMeta' | 'RequestGroup' | 'RequestGroupMeta' | 'Workspace' | 'WorkspaceMeta' | 'Project' | 'Environment' | 'ApiSpec' | 'UnitTest' | 'UnitTestSuite';\nexport default class BaseDb<T extends BaseModel> {\n private neDb: Nedb;\n constructor(target: DbTargets) {\n // @ts-ignore\n const filename = fsPath.join(window.app.getPath('userData'), `insomnia.${target}.db`);\n this.neDb = new Nedb({",
"score": 26.695558120932795
}
] | typescript | : BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) { |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
| while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) { |
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
return element.hasClass(IS_COLLAPSED);
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
return element.getAttribute(BLOCK_ATTR) === "true";
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t} else {\n\t\t\tconst next = findNextBlock(block);\n\t\t\tif (next) this.select(next as HTMLElement);\n\t\t}\n\t}\n\t/**\n\t * Select previous block or scroll to see the block's top.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */",
"score": 19.575233316895385
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 19.00694273040471
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 18.849394454761317
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t\t}\n\t\t// @ts-ignore\n\t\tconst container = context?.containerEl;\n\t\tif (this.isContainerNotInitialized(container)) {\n\t\t\tthis.initializeContainer(container);\n\t\t}\n\t\tthis.elementsToBlocks(element);\n\t}\n\t/**\n\t * Check if container is initialized.",
"score": 14.759156744087381
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t\t}\n\t}\n\t/**\n\t * Select next block or scroll to see the block's bottom.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate selectNextBlockOrScroll(block: HTMLElement) {\n\t\tif (!isBottomInView(block)) {\n\t\t\tscrollBottomIntoView(block);",
"score": 13.533079136125721
}
] | typescript | while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) { |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if ( | el.hasClass(FRONTMATTER)) return; |
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "};\n/**\n * Return the scrollable parent element of the given element\n *\n * @param node {HTMLElement} Element to start searching\n * @returns {HTMLElement | null} Scrollable parent element\n */\nconst getScrollParent = (node: HTMLElement): HTMLElement | null => {\n\tif (node == null) return null;\n\tif (node.scrollHeight > node.clientHeight) {",
"score": 21.482773366273516
},
{
"filename": "src/constants.ts",
"retrieved_chunk": " * Class name for block selector\n */\nexport const BLOCK_SELECTOR = \"rve-block-selector\";\n/**\n * Attribute name for block elements\n */\nexport const BLOCK_ATTR = \"data-rve-block\";\n/**\n * Class name for selected block\n */",
"score": 21.25934535554995
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is collapsed\n */\nconst isCollapsed = (element: HTMLElement) => {\n\treturn element.hasClass(IS_COLLAPSED);\n};\n/**\n * Find first block element inside the given element\n *",
"score": 21.186961134727156
},
{
"filename": "src/constants.ts",
"retrieved_chunk": "/**\n * Class name for the preview view\n */\nexport const MARKDOWN_PREVIEW_VIEW = \"markdown-preview-view\";\n/**\n * Class name for the frontmatter element\n */\nexport const FRONTMATTER = \"frontmatter\";\n/**\n * List of selectors for block elements",
"score": 20.085627843127654
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\t\tparent = parent.parentElement;\n\t}\n\t// If no block element found, return null\n\treturn null;\n};\n/**\n * Find previous block element to select.\n * Return null if there is no previous block element.\n *\n * @param currentElement {HTMLElement} Current element to start searching",
"score": 19.930622057632306
}
] | typescript | el.hasClass(FRONTMATTER)) return; |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof | HTMLElement && !container.hasClass(BLOCK_SELECTOR)
); |
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "\t\t\telse if (isMobileAndDisabled(plugin)) return false;\n\t\t\telse return true;\n\t\t}\n\t\t// If checking is set to false, perform an action.\n\t\telse {\n\t\t\tconst container = getReadingViewContainer(plugin);\n\t\t\tif (container) {\n\t\t\t\tplugin.blockSelector.selectTopBlockInTheView(container);\n\t\t\t}\n\t\t\treturn true;",
"score": 44.32787067689049
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 25.496823648419305
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": " *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is collapsed\n */\nconst isCollapsed = (element: HTMLElement) => {\n\treturn element.hasClass(IS_COLLAPSED);\n};\n/**\n * Find first block element inside the given element\n *",
"score": 23.201143260129108
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\telse return null;\n};\n/**\n * Check if the given element is a block element\n *\n * @param element {HTMLElement} Element to check\n * @returns {boolean} True if the element is a block element\n */\nconst isBlock = (element: HTMLElement) => {\n\treturn element.getAttribute(BLOCK_ATTR) === \"true\";",
"score": 23.1410680837299
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\t\t\tif (prevBlock) return prevBlock;\n\t\t\tparentSibling = parentSibling.previousElementSibling;\n\t\t}\n\t\tparent = parent.parentElement;\n\t}\n\t// If no block element found, return null\n\treturn null;\n};\n/**\n * Check if the given element is collapsed",
"score": 12.990476199495244
}
] | typescript | HTMLElement && !container.hasClass(BLOCK_SELECTOR)
); |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: | GitSavedWorkspace): Promise<void> { |
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData(await exportWorkspaceData(data.id))
: OldIds.createEmpty();
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 35.037510472152974
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 30.807710806013525
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 23.875525428803847
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " this.requestGroupIds.splice(index, 1);\n }\n }\n public getTestSuites(): string[] {\n return this.testSuites;\n }\n public removeTestSuites(id: string): void {\n const index = this.testSuites.indexOf(id);\n if (index !== -1) {\n this.testSuites.splice(index, 1);",
"score": 19.44023149398187
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const unittestDb = new BaseDb<UnitTest>('UnitTest');\n const unitTestSuites = await unitTestSuitesDb.findBy('parentId', workspaceId);\n for (const testSuite of unitTestSuites) {\n const tests = await unittestDb.findBy('parentId', testSuite._id);\n savedUnittestSuites.push({\n tests,\n testSuite,\n });\n }\n return savedUnittestSuites;",
"score": 19.09126612921412
}
] | typescript | GitSavedWorkspace): Promise<void> { |
import { BLOCK_ATTR, IS_COLLAPSED, MARKDOWN_PREVIEW_VIEW } from "../constants";
export const isBottomInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.bottom <= window.innerHeight;
};
export const scrollBottomIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.bottom - scrollable.clientHeight + 200,
});
};
export const isTopInView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
return rect.top >= 0;
};
export const scrollTopIntoView = (block: HTMLElement) => {
const rect = block.getBoundingClientRect();
const scrollable = getScrollParent(block);
scrollable?.scrollBy({
behavior: "auto",
top: rect.top - 200,
});
};
/**
* Find next block element to select.
* Return null if there is no next block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Next block element
*/
export const findNextBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
let nextBlock = null;
// Start by checking if there's a block element inside the current element
if (!isCollapsed(currentElement)) {
const children = currentElement.children;
for (let i = 0; i < children.length; i++) {
nextBlock = findBlock(children[i] as HTMLElement);
if (nextBlock) return nextBlock;
}
}
// Check next siblings of current element
let nextSibling = currentElement.nextElementSibling;
while (nextSibling) {
nextBlock = findBlock(nextSibling as HTMLElement);
if (nextBlock) return nextBlock;
nextSibling = nextSibling.nextElementSibling;
}
// Check next siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.hasClass(MARKDOWN_PREVIEW_VIEW)) {
let parentSibling = parent.nextElementSibling;
while (parentSibling) {
nextBlock = findBlock(parentSibling as HTMLElement);
if (nextBlock) return nextBlock;
parentSibling = parentSibling.nextElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Find previous block element to select.
* Return null if there is no previous block element.
*
* @param currentElement {HTMLElement} Current element to start searching
* @returns {HTMLElement | null} Previous block element
*/
export const findPreviousBlock = (
currentElement: HTMLElement
): HTMLElement | null => {
// Check previous siblings of current element
let prevSibling = currentElement.previousElementSibling;
while (prevSibling) {
const prevBlock = findLastBlock(prevSibling as HTMLElement);
if (prevBlock) return prevBlock;
prevSibling = prevSibling.previousElementSibling;
}
// Check previous siblings of parent block element
let parent = currentElement.parentElement;
while (parent && !parent.classList.contains(MARKDOWN_PREVIEW_VIEW)) {
// Check ancestors of current element first
if (isBlock(parent)) return parent;
let parentSibling = parent.previousElementSibling;
while (parentSibling) {
const prevBlock = findLastBlock(parentSibling as HTMLElement);
if (prevBlock) return prevBlock;
parentSibling = parentSibling.previousElementSibling;
}
parent = parent.parentElement;
}
// If no block element found, return null
return null;
};
/**
* Check if the given element is collapsed
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is collapsed
*/
const isCollapsed = (element: HTMLElement) => {
return | element.hasClass(IS_COLLAPSED); |
};
/**
* Find first block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} First block element
*/
const findBlock = (element: HTMLElement): HTMLElement | null => {
if (isBlock(element)) {
return element;
}
let block = null;
const childElements = element.children;
for (let i = 0; i < childElements.length; i++) {
block = findBlock(childElements[i] as HTMLElement);
if (block) return block;
}
return null;
};
/**
* Find last block element inside the given element
*
* @param element {HTMLElement} Element to search
* @returns {HTMLElement | null} Last block element
*/
const findLastBlock = (element: HTMLElement): HTMLElement | null => {
if (isCollapsed(element) && isBlock(element)) return element;
let block = null;
const childElements = element.children;
for (let i = childElements.length - 1; i >= 0; i--) {
block = findLastBlock(childElements[i] as HTMLElement);
if (block) return block;
}
if (isBlock(element)) return element;
else return null;
};
/**
* Check if the given element is a block element
*
* @param element {HTMLElement} Element to check
* @returns {boolean} True if the element is a block element
*/
const isBlock = (element: HTMLElement) => {
return element.getAttribute(BLOCK_ATTR) === "true";
};
/**
* Return the scrollable parent element of the given element
*
* @param node {HTMLElement} Element to start searching
* @returns {HTMLElement | null} Scrollable parent element
*/
const getScrollParent = (node: HTMLElement): HTMLElement | null => {
if (node == null) return null;
if (node.scrollHeight > node.clientHeight) {
return node;
} else {
return getScrollParent(node.parentNode as HTMLElement);
}
};
| src/block-selector/selection-util.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t *\n\t * @param container {MarkdownPostProcessorContext.containerEl} Container element\n\t * @returns {boolean} True if container is initialized\n\t */\n\tprivate isContainerNotInitialized(container: HTMLElement) {\n\t\treturn (\n\t\t\tcontainer instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)\n\t\t);\n\t}\n\t/**",
"score": 34.687305964563784
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set `data-rve-block` attribute to block elements.\n\t *\n\t * @param element {HTMLElement} Element to start searching\n\t */\n\tprivate elementsToBlocks(element: HTMLElement) {\n\t\tconst elements = element.querySelectorAll(BLOCKS.join(\", \"));\n\t\telements.forEach((el) => {\n\t\t\tif (el.hasClass(FRONTMATTER)) return;",
"score": 29.220851180209728
},
{
"filename": "src/block-selector/index.ts",
"retrieved_chunk": "\t\t}\n\t\t// @ts-ignore\n\t\tconst container = context?.containerEl;\n\t\tif (this.isContainerNotInitialized(container)) {\n\t\t\tthis.initializeContainer(container);\n\t\t}\n\t\tthis.elementsToBlocks(element);\n\t}\n\t/**\n\t * Check if container is initialized.",
"score": 22.077453641141016
},
{
"filename": "src/constants.ts",
"retrieved_chunk": "export const SELECTED_BLOCK = \"rve-selected-block\";\n/**\n * Selector for collapse indicators\n */\nexport const COLLAPSE_INDICATORS = [\".collapse-indicator\", \".callout-fold\"];\n/**\n * Class name for collapsed block\n */\nexport const IS_COLLAPSED = \"is-collapsed\";",
"score": 21.43455162671556
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 21.301930036551262
}
] | typescript | element.hasClass(IS_COLLAPSED); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
this.selectionHandler.onBlockClick(e)
);
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
| const elements = element.querySelectorAll(BLOCKS.join(", ")); |
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "};\n/**\n * Return the scrollable parent element of the given element\n *\n * @param node {HTMLElement} Element to start searching\n * @returns {HTMLElement | null} Scrollable parent element\n */\nconst getScrollParent = (node: HTMLElement): HTMLElement | null => {\n\tif (node == null) return null;\n\tif (node.scrollHeight > node.clientHeight) {",
"score": 19.42661469120886
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\tscrollable?.scrollBy({\n\t\tbehavior: \"auto\",\n\t\ttop: rect.top - 200,\n\t});\n};\n/**\n * Find next block element to select.\n * Return null if there is no next block element.\n *\n * @param currentElement {HTMLElement} Current element to start searching",
"score": 17.86388617063111
},
{
"filename": "src/block-selector/selection-util.ts",
"retrieved_chunk": "\t\tparent = parent.parentElement;\n\t}\n\t// If no block element found, return null\n\treturn null;\n};\n/**\n * Find previous block element to select.\n * Return null if there is no previous block element.\n *\n * @param currentElement {HTMLElement} Current element to start searching",
"score": 17.65686592797294
},
{
"filename": "src/constants.ts",
"retrieved_chunk": " * Class name for block selector\n */\nexport const BLOCK_SELECTOR = \"rve-block-selector\";\n/**\n * Attribute name for block elements\n */\nexport const BLOCK_ATTR = \"data-rve-block\";\n/**\n * Class name for selected block\n */",
"score": 17.439356706147763
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 16.782014792093243
}
] | typescript | const elements = element.querySelectorAll(BLOCKS.join(", ")); |
import { MarkdownPostProcessorContext, Platform } from "obsidian";
import ReadingViewEnhancer from "src/main";
import SelectionHandler from "./selection-handler";
import { BLOCKS, BLOCK_ATTR, BLOCK_SELECTOR, FRONTMATTER } from "../constants";
/**
* BlockSelector enables to navigate between blocks and fold/unfold blocks.
*
* Block elements are elements that are having block level elements.
* For example, a paragraph is a block element.
*
* You can select a block by clicking on it and then use arrow keys to navigate between blocks.
* For selected block, the background color will be changed.
* You can also use `ArrowLeft` and `ArrowRight` to fold/unfold blocks.
* Foldable blocks are having `collapse-indicator` or `callout-fold` class.
*/
export default class BlockSelector {
plugin: ReadingViewEnhancer;
selectionHandler: SelectionHandler;
selectedBlock: HTMLElement | null;
/**
* Initialize BlockSelector.
* Register markdown post processor to blockify some elements.
*
* @param plugin {ReadingViewEnhancer} Plugin instance
*/
constructor(plugin: ReadingViewEnhancer) {
this.plugin = plugin;
this.selectionHandler = new SelectionHandler();
}
/**
* Activate BlockSelector
*/
activate() {
this.plugin.registerMarkdownPostProcessor(this.blockify.bind(this));
}
/**
* Select top block in the view
*
* @param viewContainer {HTMLElement} View container element
*/
selectTopBlockInTheView(viewContainer: HTMLElement) {
this.selectionHandler.selectTopBlockInTheView(viewContainer);
}
/**
* Blockify some elements.
* If container is not initialized, initialize it.
* Transform some elements to block elements.
*/
private blockify(
element: HTMLElement,
context: MarkdownPostProcessorContext
) {
// If block selector is disabled, do nothing
if (!this.plugin.settings.enableBlockSelector) return;
// If it's mobile but block selector is disabled on mobile, do nothing
if (
(Platform.isMobile || Platform.isMobileApp) &&
this.plugin.settings.disableBlockSelectorOnMobile
) {
return;
}
// @ts-ignore
const container = context?.containerEl;
if (this.isContainerNotInitialized(container)) {
this.initializeContainer(container);
}
this.elementsToBlocks(element);
}
/**
* Check if container is initialized.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
* @returns {boolean} True if container is initialized
*/
private isContainerNotInitialized(container: HTMLElement) {
return (
container instanceof HTMLElement && !container.hasClass(BLOCK_SELECTOR)
);
}
/**
* Initialize container.
* Add some event listeners to container.
*
* @param container {MarkdownPostProcessorContext.containerEl} Container element
*/
private initializeContainer(container: HTMLElement) {
// Mark container as initialized
container.addClass(BLOCK_SELECTOR);
// On click, select block element
container.addEventListener("click", (e) =>
| this.selectionHandler.onBlockClick(e)
); |
// On focusout, unselect block element
container.addEventListener("focusout", () =>
this.selectionHandler.unselect()
);
// On keydown, navigate between blocks or fold/unfold blocks
container.addEventListener("keydown", (e) =>
this.selectionHandler.onKeyDown(e)
);
}
/**
* Set `data-rve-block` attribute to block elements.
*
* @param element {HTMLElement} Element to start searching
*/
private elementsToBlocks(element: HTMLElement) {
const elements = element.querySelectorAll(BLOCKS.join(", "));
elements.forEach((el) => {
if (el.hasClass(FRONTMATTER)) return;
el.setAttribute(BLOCK_ATTR, "true");
el.setAttribute("tabindex", "-1");
});
}
}
| src/block-selector/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/commands/commands.ts",
"retrieved_chunk": "\t\t\telse if (isMobileAndDisabled(plugin)) return false;\n\t\t\telse return true;\n\t\t}\n\t\t// If checking is set to false, perform an action.\n\t\telse {\n\t\t\tconst container = getReadingViewContainer(plugin);\n\t\t\tif (container) {\n\t\t\t\tplugin.blockSelector.selectTopBlockInTheView(container);\n\t\t\t}\n\t\t\treturn true;",
"score": 30.39247782945335
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Trigger 'select' on clicked block element.\n\t *\n\t * @param e {MouseEvent} Mouse event\n\t */\n\tonBlockClick(e: MouseEvent) {\n\t\tconst target = e.target as HTMLElement;\n\t\tconst block = target.closest(`[${BLOCK_ATTR}=true]`);\n\t\tif (block instanceof HTMLElement) {",
"score": 23.72200975199103
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * Fold/Unfold block.\n\t *\n\t * @param block {HTMLElement} Block element\n\t */\n\tprivate toggleFold(block: HTMLElement) {\n\t\tconst collapseIndicator = block.querySelector(\n\t\t\tCOLLAPSE_INDICATORS.join(\",\")\n\t\t) as HTMLElement;\n\t\tif (collapseIndicator) {\n\t\t\tcollapseIndicator.click();",
"score": 18.86912283104765
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t *\n\t * @param viewContainer {HTMLElement} View container element\n\t */\n\tselectTopBlockInTheView(viewContainer: HTMLElement) {\n\t\tconst blocks = viewContainer.querySelectorAll(`[${BLOCK_ATTR}=true]`);\n\t\t// If there is no block, do nothing\n\t\tif (blocks.length === 0) return;\n\t\t// Get the index of the topmost block in the view\n\t\tlet topIndex = -1;\n\t\tfor (let i = 0; i < blocks.length; i++) {",
"score": 17.789672252265294
},
{
"filename": "src/block-selector/selection-handler.ts",
"retrieved_chunk": "\t * If selected block is too long,\n\t * `ArrowDown` and `ArrowUp` scrolls to see the element's bottom or top.\n\t * This is for loading adjacent blocks which are not in the DOM tree.\n\t *\n\t * @param e {KeyboardEvent} Keyboard event\n\t * @param scrollable {HTMLElement} Scrollable parent element\n\t */\n\tonKeyDown(e: KeyboardEvent) {\n\t\tconst block = e.target as HTMLElement;\n\t\tif (e.key === \"ArrowDown\") {",
"score": 16.189028849828937
}
] | typescript | this.selectionHandler.onBlockClick(e)
); |
import { Plugin } from "obsidian";
import RveStyles, { BlockColorRule } from "./styles";
import { RveSettingTab, RveSettings, DEFAULT_SETTINGS } from "./settings";
import Commands from "./commands";
import BlockSelector from "./block-selector";
export default class ReadingViewEnhancer extends Plugin {
settings: RveSettings;
styles: RveStyles;
blockSelector: BlockSelector;
/**
* On load,
*
* - Load settings & styles
* - Activate block selector
* - It actually do its work if settings.enableBlockSelector is true
* - Register all commands
* - Add settings tab
*/
async onload() {
// Settings & Styles
await this.loadSettings();
this.styles = new RveStyles();
this.app.workspace.onLayoutReady(() => this.applySettingsToStyles());
// Activate block selector.
this.blockSelector = new BlockSelector(this);
this.blockSelector.activate();
// Register commands
new Commands(this).register();
// Add settings tab at last
this.addSettingTab(new RveSettingTab(this));
// Leave a message in the console
console.log("Loaded 'Reading View Enhancer'");
}
/**
* On unload,
*
* - Remove all styles
*/
async onunload() {
this.styles.cleanup();
// Leave a message in the console
console.log("Unloaded 'Reading View Enhancer'");
}
// ===================================================================
/**
* Load settings
*/
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
/**
* Save settings
*/
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Apply settings to styles
*
* - Apply block color
* - Apply always on collapse indicator
* - Apply prevent table overflowing
* - Apply scrollable code
*/
private applySettingsToStyles() {
this.applyBlockColor();
this.applyAlwaysOnCollapse();
this.applyPreventTableOverflowing();
this.applyScrollableCode();
this.styles.apply();
}
/**
* Apply block color
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyBlockColor(isImmediate = false) {
const blockColor = this.styles.of("block-color") as BlockColorRule;
| blockColor.set(this.settings.blockColor); |
if (isImmediate) this.styles.apply();
}
/**
* Apply always on collapse indicator
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyAlwaysOnCollapse(isImmediate = false) {
this.styles.of("collapse-indicator").isActive =
this.settings.alwaysOnCollapseIndicator;
if (isImmediate) this.styles.apply();
}
/**
* Apply prevent table overflowing
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyPreventTableOverflowing(isImmediate = false) {
this.styles.of("prevent-table-overflowing").isActive =
this.settings.preventTableOverflowing;
if (isImmediate) this.styles.apply();
}
/**
* Apply scrollable code
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyScrollableCode(isImmediate = false) {
this.styles.of("scrollable-code").isActive = this.settings.scrollableCode;
if (isImmediate) this.styles.apply();
}
}
| src/main.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set the block color\n\t *\n\t * @param blockColor {string} The block color\n\t */\n\tset(blockColor: string) {\n\t\tthis.blockColor = blockColor;\n\t}\n}",
"score": 27.288226926431072
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t * Also, creates a button to set color to the current accent color.\n\t *\n\t * @param color {ColorComponent} Color component\n\t */\n\tcolorPicker(color: ColorComponent) {\n\t\tconst { settings } = this.plugin;\n\t\tcolor.setValue(settings.blockColor).onChange((changed) => {\n\t\t\t// save on change\n\t\t\tsettings.blockColor = toHex(changed);\n\t\t\tthis.plugin.saveSettings();",
"score": 24.848885577507765
},
{
"filename": "src/settings/index.ts",
"retrieved_chunk": "\tscrollableCode: boolean;\n}\nexport const DEFAULT_SETTINGS: RveSettings = {\n\tblockColor: \"#8b6cef\", // Obsidian default color\n\tenableBlockSelector: false,\n\tdisableBlockSelectorOnMobile: false,\n\talwaysOnCollapseIndicator: false,\n\tpreventTableOverflowing: false,\n\tscrollableCode: false,\n};",
"score": 22.674204040624456
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t */\n\taccentColorButton(button: ButtonComponent, color: ColorComponent) {\n\t\tbutton.setButtonText(\"Use current accent color\").onClick(() => {\n\t\t\tconst accentColor = this.getAccentColor();\n\t\t\tcolor.setValue(accentColor);\n\t\t\tthis.plugin.settings.blockColor = accentColor;\n\t\t\tthis.plugin.saveSettings();\n\t\t\tthis.plugin.applyBlockColor(true);\n\t\t});\n\t}",
"score": 20.446375159247605
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\treturn this.injectVariables(this.template);\n\t}\n}\n/**\n * Block color rule.\n *\n * Accepts a block color and injects it into the template.\n */\nexport class BlockColorRule extends StyleRule {\n\tprivate blockColor: string;",
"score": 18.443119012727845
}
] | typescript | blockColor.set(this.settings.blockColor); |
import { PluginSettingTab } from "obsidian";
import ReadingViewEnhancer from "../main";
import BlockSelectorSettings from "./block";
import MiscellaneousSettings from "./miscellaneous";
export interface RveSettings {
blockColor: string;
enableBlockSelector: boolean;
disableBlockSelectorOnMobile: boolean;
alwaysOnCollapseIndicator: boolean;
preventTableOverflowing: boolean;
scrollableCode: boolean;
}
export const DEFAULT_SETTINGS: RveSettings = {
blockColor: "#8b6cef", // Obsidian default color
enableBlockSelector: false,
disableBlockSelectorOnMobile: false,
alwaysOnCollapseIndicator: false,
preventTableOverflowing: false,
scrollableCode: false,
};
// ===================================================================
/**
* Settings tab.
* In this tab, you can change settings.
*
* - Block color
* - Enable/Disable Block Selector
*/
export class RveSettingTab extends PluginSettingTab {
plugin: ReadingViewEnhancer;
constructor(plugin: ReadingViewEnhancer) {
super(app, plugin);
this.plugin = plugin;
}
/**
* Displays settings tab.
*/
display() {
const { containerEl } = this;
// Clear all first
containerEl.empty();
// Add header
containerEl.createEl("h1", { text: "Reading View Enhancer" });
// Add block selector settings
| new BlockSelectorSettings(containerEl, this.plugin); |
// Add miscellaneous settings
new MiscellaneousSettings(containerEl, this.plugin);
}
}
| src/settings/index.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "import ReadingViewEnhancer from \"src/main\";\nimport BlockColorSetting from \"./block-color\";\nimport EnableBlockSelectorSetting from \"./block-selector\";\nimport DisableBlockSelectorOnMobileSetting from \"./block-selector-mobile\";\n/**\n * Registers settings components related to block selector.\n */\nexport default class BlockSelectorSettings {\n\tconstructor(containerEl: HTMLElement, plugin: ReadingViewEnhancer) {\n\t\tcontainerEl.createEl(\"h2\", { text: \"Block Selector\" });",
"score": 25.648744794209485
},
{
"filename": "src/settings/miscellaneous/index.ts",
"retrieved_chunk": "\t\tnew BlockColorSetting(containerEl, plugin);\n\t\tnew EnableBlockSelectorSetting(containerEl, plugin);\n\t\tnew DisableBlockSelectorOnMobileSetting(containerEl, plugin);\n\t}\n}",
"score": 22.78354606304834
},
{
"filename": "src/settings/block/index.ts",
"retrieved_chunk": "\t\tnew AlwaysOnCollapseIndicatorSetting(containerEl, plugin);\n\t\tnew PreventTableOverflowingSetting(containerEl, plugin);\n\t\tnew ScrollableCodeSetting(containerEl, plugin);\n\t}\n}",
"score": 22.78354606304834
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t * On load,\n\t *\n\t * - Load settings & styles\n\t * - Activate block selector\n\t * - It actually do its work if settings.enableBlockSelector is true\n\t * - Register all commands\n\t * - Add settings tab\n\t */\n\tasync onload() {\n\t\t// Settings & Styles",
"score": 20.288060028365887
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\tawait this.loadSettings();\n\t\tthis.styles = new RveStyles();\n\t\tthis.app.workspace.onLayoutReady(() => this.applySettingsToStyles());\n\t\t// Activate block selector.\n\t\tthis.blockSelector = new BlockSelector(this);\n\t\tthis.blockSelector.activate();\n\t\t// Register commands\n\t\tnew Commands(this).register();\n\t\t// Add settings tab at last\n\t\tthis.addSettingTab(new RveSettingTab(this));",
"score": 19.079279326166
}
] | typescript | new BlockSelectorSettings(containerEl, this.plugin); |
import { Plugin } from "obsidian";
import RveStyles, { BlockColorRule } from "./styles";
import { RveSettingTab, RveSettings, DEFAULT_SETTINGS } from "./settings";
import Commands from "./commands";
import BlockSelector from "./block-selector";
export default class ReadingViewEnhancer extends Plugin {
settings: RveSettings;
styles: RveStyles;
blockSelector: BlockSelector;
/**
* On load,
*
* - Load settings & styles
* - Activate block selector
* - It actually do its work if settings.enableBlockSelector is true
* - Register all commands
* - Add settings tab
*/
async onload() {
// Settings & Styles
await this.loadSettings();
this.styles = new RveStyles();
this.app.workspace.onLayoutReady(() => this.applySettingsToStyles());
// Activate block selector.
this.blockSelector = new BlockSelector(this);
this.blockSelector.activate();
// Register commands
new Commands(this).register();
// Add settings tab at last
this.addSettingTab(new RveSettingTab(this));
// Leave a message in the console
console.log("Loaded 'Reading View Enhancer'");
}
/**
* On unload,
*
* - Remove all styles
*/
async onunload() {
this.styles.cleanup();
// Leave a message in the console
console.log("Unloaded 'Reading View Enhancer'");
}
// ===================================================================
/**
* Load settings
*/
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
/**
* Save settings
*/
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Apply settings to styles
*
* - Apply block color
* - Apply always on collapse indicator
* - Apply prevent table overflowing
* - Apply scrollable code
*/
private applySettingsToStyles() {
this.applyBlockColor();
this.applyAlwaysOnCollapse();
this.applyPreventTableOverflowing();
this.applyScrollableCode();
this.styles.apply();
}
/**
* Apply block color
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyBlockColor(isImmediate = false) {
const blockColor = this.styles | .of("block-color") as BlockColorRule; |
blockColor.set(this.settings.blockColor);
if (isImmediate) this.styles.apply();
}
/**
* Apply always on collapse indicator
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyAlwaysOnCollapse(isImmediate = false) {
this.styles.of("collapse-indicator").isActive =
this.settings.alwaysOnCollapseIndicator;
if (isImmediate) this.styles.apply();
}
/**
* Apply prevent table overflowing
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyPreventTableOverflowing(isImmediate = false) {
this.styles.of("prevent-table-overflowing").isActive =
this.settings.preventTableOverflowing;
if (isImmediate) this.styles.apply();
}
/**
* Apply scrollable code
*
* @param isImmediate {boolean} Whether to apply styles immediately
*/
applyScrollableCode(isImmediate = false) {
this.styles.of("scrollable-code").isActive = this.settings.scrollableCode;
if (isImmediate) this.styles.apply();
}
}
| src/main.ts | Galacsh-obsidian-reading-view-enhancer-8ee0af2 | [
{
"filename": "src/settings/index.ts",
"retrieved_chunk": "\tscrollableCode: boolean;\n}\nexport const DEFAULT_SETTINGS: RveSettings = {\n\tblockColor: \"#8b6cef\", // Obsidian default color\n\tenableBlockSelector: false,\n\tdisableBlockSelectorOnMobile: false,\n\talwaysOnCollapseIndicator: false,\n\tpreventTableOverflowing: false,\n\tscrollableCode: false,\n};",
"score": 16.777308901066665
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t\treturn this.rules[rule];\n\t}\n\t/**\n\t * Apply all active rules\n\t */\n\tapply() {\n\t\tconst style = Object.values(this.rules)\n\t\t\t.filter((rule) => rule.isActive)\n\t\t\t.map((rule) => rule.getRule())\n\t\t\t.join(\"\\n\");",
"score": 14.859786899195269
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t */\n\taccentColorButton(button: ButtonComponent, color: ColorComponent) {\n\t\tbutton.setButtonText(\"Use current accent color\").onClick(() => {\n\t\t\tconst accentColor = this.getAccentColor();\n\t\t\tcolor.setValue(accentColor);\n\t\t\tthis.plugin.settings.blockColor = accentColor;\n\t\t\tthis.plugin.saveSettings();\n\t\t\tthis.plugin.applyBlockColor(true);\n\t\t});\n\t}",
"score": 13.31828614667118
},
{
"filename": "src/styles.ts",
"retrieved_chunk": "\t}\n\t/**\n\t * Set the block color\n\t *\n\t * @param blockColor {string} The block color\n\t */\n\tset(blockColor: string) {\n\t\tthis.blockColor = blockColor;\n\t}\n}",
"score": 12.963985208713046
},
{
"filename": "src/settings/block/block-color.ts",
"retrieved_chunk": "\t * Also, creates a button to set color to the current accent color.\n\t *\n\t * @param color {ColorComponent} Color component\n\t */\n\tcolorPicker(color: ColorComponent) {\n\t\tconst { settings } = this.plugin;\n\t\tcolor.setValue(settings.blockColor).onChange((changed) => {\n\t\t\t// save on change\n\t\t\tsettings.blockColor = toHex(changed);\n\t\t\tthis.plugin.saveSettings();",
"score": 12.863091907536269
}
] | typescript | .of("block-color") as BlockColorRule; |
import { join } from 'node:path';
import fs from 'node:fs';
import BaseDb from './db/BaseDb';
import { exportWorkspaceData } from './exportData';
import { Workspace, WorkspaceMeta, BaseRequest, RequestMeta, RequestGroup, RequestGroupMeta, Environment, Project, ApiSpec, UnittestSuite, UnitTest } from './insomniaDbTypes';
import OldIds from './OldIds';
import { GitSavedRequest, GitSavedWorkspace, GitSavedProject } from './types';
export function readProjectData(path: string): [GitSavedProject, GitSavedWorkspace[]] {
// Read the Project file
const projectFile = join(path, 'project.json');
// TODO: Validate this using Zod
const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());
// Read all the workspace data
const workspaceData: GitSavedWorkspace[] = [];
for (const workspaceId of project.workspaceIds) {
const workspaceFile = join(path, workspaceId + '.json');
// TODO: Validate this using Zod
const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());
workspaceData.push(workspace);
}
return [project, workspaceData];
}
export async function importProject(project: GitSavedProject, workspaces: GitSavedWorkspace[]) {
// Upsert the Project
const projectDb = new BaseDb<Project>('Project');
await projectDb.upsert({
_id: project.id,
name: project.name,
remoteId: project.remoteId,
created: Date.now(),
isPrivate: false,
modified: Date.now(),
parentId: null,
type: 'Project',
});
const workspaceDb = new BaseDb<Workspace>('Workspace');
const workspaceMetaDb = new BaseDb<Workspace>('WorkspaceMeta');
let oldWorkspaces = (await workspaceDb.findBy('parentId', project.id)).map((ws) => ws._id);
// Update all Workspaces
for (const workspace of workspaces) {
oldWorkspaces = oldWorkspaces.filter((oldWs) => oldWs !== workspace.id);
await importWorkspaceData(workspace);
}
// Delete old workspaces
for (const oldWorkspace of oldWorkspaces) {
await workspaceDb.deleteBy('_id', oldWorkspace);
await workspaceMetaDb.deleteBy('parentId', oldWorkspace);
}
}
async function upsertRequestsRecursive(
requests: GitSavedRequest[],
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
) {
for (const request of requests) {
if (request.type === 'group') {
await requestGroupDb.upsert(request.group);
await requestGroupMetaDb.upsert(request.meta);
oldIds.removeRequestGroupId(request.id);
await upsertRequestsRecursive(request.children, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
continue;
}
await requestDb.upsert(request.request);
await requestMetaDb.upsert(request.meta);
oldIds.removeRequestId(request.id);
}
}
async function removeOldData(
oldIds: OldIds,
requestDb: BaseDb<BaseRequest>,
requestMetaDb: BaseDb<RequestMeta>,
requestGroupDb: BaseDb<RequestGroup>,
requestGroupMetaDb: BaseDb<RequestGroupMeta>,
environmentDb: BaseDb<Environment>,
testSuitesDb: BaseDb<UnittestSuite>,
testDb: BaseDb<UnitTest>,
) {
for (const envId of oldIds.getEnvironmentIds()) {
await environmentDb.deleteBy('_id', envId);
}
for (const requestId of oldIds.getRequestIds()) {
await requestDb.deleteBy('_id', requestId);
await requestMetaDb.deleteBy('parentId', requestId);
}
for (const requestGroupId of oldIds.getRequestGroupId()) {
await requestGroupDb.deleteBy('_id', requestGroupId);
await requestGroupMetaDb.deleteBy('parentId', requestGroupId);
}
for (const testSuites of oldIds.getTestSuites()) {
await testSuitesDb.deleteBy('_id', testSuites);
}
for (const test of oldIds.getTests()) {
await testDb.deleteBy('_id', test);
}
}
export async function importWorkspaceData(data: GitSavedWorkspace): Promise<void> {
const workspaceDb = new BaseDb<Workspace>('Workspace');
// Collect OldIds of Requests / Folders so we can delete deleted Docs at the end
const oldIds = await workspaceDb.findById(data.id)
? OldIds.fromOldData( | await exportWorkspaceData(data.id))
: OldIds.createEmpty(); |
// Update Workspace metadata
await workspaceDb.upsert(data.workspace);
const workspaceMetaDb = new BaseDb<WorkspaceMeta>('WorkspaceMeta');
const fullMeta: WorkspaceMeta = {
...data.meta,
// These are the Default value from 'models/workspace-meta::init()'. TODO: Load the old WorkspaceMetadata here
activeUnitTestSuiteId: null,
cachedGitLastAuthor: null,
cachedGitLastCommitTime: null,
cachedGitRepositoryBranch: null,
gitRepositoryId: null,
hasSeen: true,
paneHeight: 0.5,
paneWidth: 0.5,
parentId: data.id,
sidebarFilter: '',
sidebarHidden: false,
sidebarWidth: 19,
pushSnapshotOnInitialize: false,
};
await workspaceMetaDb.upsert(fullMeta);
const requestDb = new BaseDb<BaseRequest>('Request');
const requestMetaDb = new BaseDb<RequestMeta>('RequestMeta');
const requestGroupDb = new BaseDb<RequestGroup>('RequestGroup');
const requestGroupMetaDb = new BaseDb<RequestGroupMeta>('RequestGroupMeta');
await upsertRequestsRecursive(data.requests, oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb);
const environmentDb = new BaseDb<Environment>('Environment');
for (const environment of data.environments) {
await environmentDb.upsert(environment);
oldIds.removeEnvironmentId(environment._id);
}
if (data.apiSpec) {
const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');
await apiSpecDb.upsert(data.apiSpec);
}
const unitTestSuitesDb = new BaseDb<UnittestSuite>('UnitTestSuite');
const unitTestDb = new BaseDb<UnitTest>('UnitTest');
for (const testSuite of data.unitTestSuites) {
await unitTestSuitesDb.upsert(testSuite.testSuite);
oldIds.removeTestSuites(testSuite.testSuite._id);
for (const test of testSuite.tests) {
await unitTestDb.upsert(test);
oldIds.removeTest(test._id);
}
}
await removeOldData(
oldIds, requestDb, requestMetaDb, requestGroupDb, requestGroupMetaDb, environmentDb, unitTestSuitesDb, unitTestDb,
);
}
| src/importData.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " return new OldIds([], [], [], [], []);\n }\n public static fromOldData(data: GitSavedWorkspace): OldIds {\n const environmentIds = data.environments.map((env) => env._id);\n const requestIds = [];\n const requestGroupIds = [];\n OldIds.getIdsRecursive(data.requests, requestIds, requestGroupIds);\n const tests = [];\n const testSuites = data.unitTestSuites.map((testSuite) => {\n for (const test of testSuite.tests) {",
"score": 48.63005813753324
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": "}\nasync function getApiSpec(workspaceId: string): Promise<ApiSpec | null> {\n const apiSpecDb = new BaseDb<ApiSpec>('ApiSpec');\n const apiSpecs = await apiSpecDb.findBy('parentId', workspaceId);\n return apiSpecs[0] ?? null;\n}\nexport async function exportWorkspaceData(workspaceId: string): Promise<GitSavedWorkspace> {\n // Find workspace\n const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspace = await workspaceDb.findById(workspaceId);",
"score": 45.71486194248867
},
{
"filename": "src/exportData.ts",
"retrieved_chunk": " const workspaceDb = new BaseDb<Workspace>('Workspace');\n const workspaces = await workspaceDb.findBy('parentId', fullProject._id);\n const savedWorkspaces: GitSavedWorkspace[] = [];\n for (const workspace of workspaces) {\n savedWorkspaces.push(await exportWorkspaceData(workspace._id));\n project.workspaceIds.push(workspace._id);\n }\n return [project, savedWorkspaces];\n}\n// ParentId is either the WorkspaceId for TopLevel requests or an FolderId for nested requests",
"score": 38.72810118995458
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": " tests.push(test._id);\n }\n return testSuite.testSuite._id;\n });\n return new OldIds(environmentIds, requestIds, requestGroupIds, testSuites, tests);\n }\n private static getIdsRecursive(requests: GitSavedRequest[], requestIds: string[], requestGroupIds: string[]) {\n for (const request of requests) {\n if (request.type === 'group') {\n requestGroupIds.push(request.id);",
"score": 25.332356660751024
},
{
"filename": "src/OldIds.ts",
"retrieved_chunk": "import { GitSavedRequest, GitSavedWorkspace } from './types';\nexport default class OldIds {\n private constructor(\n private environmentIds: string[],\n private requestIds: string[],\n private requestGroupIds: string[],\n private testSuites: string[],\n private tests: string[],\n ) {}\n public static createEmpty(): OldIds {",
"score": 25.02224373801363
}
] | typescript | await exportWorkspaceData(data.id))
: OldIds.createEmpty(); |
import {COMPOSE_CONTENT_EDITABLE, COMPOSE_LINK_CARD_BUTTON} from '../dom/selectors';
import {log} from '../utils/logger';
import {typeText, backspace} from '../utils/text';
import {Pipeline} from './pipeline';
import {ultimatelyFind} from '../dom/utils';
import {EventKeeper} from '../utils/eventKeeper';
const STAGING_URL_REGEX = /.*(https:\/\/staging\.bsky\.app\/profile\/.*\/post\/.*\/?)$/;
const URL_REGEX = /.*(https:\/\/bsky\.app\/profile\/.*\/post\/.*\/?)$/;
export class QuotePostPipeline extends Pipeline {
#modal: HTMLElement | null;
#contentEditable: HTMLElement | null;
readonly #eventKeeper: EventKeeper;
constructor() {
super();
this.#modal = null;
this.#contentEditable = null;
this.#eventKeeper = new EventKeeper();
}
deploy(modal: HTMLElement): void {
if (this.#modal !== null) {
log('QuotePostPipeline is already deployed');
return;
}
this.#modal = modal;
ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {
this.#contentEditable = contentEditable;
this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});
});
}
terminate(): void {
if (this.#modal === null) {
log('QuotePostPipeline is not deployed');
return;
}
this.#eventKeeper.cancelAll();
this.#modal = this.#contentEditable = null;
}
onPaste(event: ClipboardEvent): void {
if (!event.clipboardData || !this.#contentEditable) return;
if (event.clipboardData.types.indexOf('text/plain') === -1) return;
event.preventDefault();
const contentEditable = this.#contentEditable;
let data = event.clipboardData.getData('text/plain');
if (data.match(STAGING_URL_REGEX) !== null) {
data = data.replace('https://staging.bsky.app/', 'https://bsky.app/');
}
contentEditable.focus();
typeText(data);
typeText(' '); // Add a space after the link for it to resolve as one
// Wait for the text to be inserted into the contentEditable
setTimeout(() => {
const lastChar = contentEditable.textContent?.slice(-1) ?? '';
if (lastChar === ' ') backspace();
if (data.match(URL_REGEX) !== null) {
this. | #modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => { |
linkCardButton.click();
});
}
}, 50);
}
}
| src/content/pipelines/quotePost.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/hacks/emojiDataWrapper.ts",
"retrieved_chunk": "import * as data from '@emoji-mart/data';\n// This is done to make `data.categories` amenable to being rewritten by the emoji-mart library\nexport const emojiData = { ...data };",
"score": 32.25225268809419
},
{
"filename": "src/content/main.ts",
"retrieved_chunk": " log('Launched');\n}).catch(() => {\n setTimeout(() => {\n run().then(() => {\n log('Launched after the second attempt (1000ms delay)');\n }).catch((e) => {\n if (e === EXTENSION_DISABLED_CODE) return;\n console.error(`Failed to launch Bluesky Overhaul. Please, copy the error and report this issue: ${REPO_LINK}`);\n console.error(e);\n });",
"score": 28.302266057693913
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " }\n this.#modal = modal;\n this.#picker = this.#createPicker();\n Promise.all([\n ultimatelyFind(modal, [COMPOSE_PHOTO_BUTTON]),\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE)\n ]).then(([photoButton, contentEditable]) => {\n this.#elems.photoButton = photoButton;\n this.#elems.contentEditable = contentEditable;\n this.#elems.emojiButton = createEmojiButton(this.#elems.photoButton);",
"score": 27.51480458109661
},
{
"filename": "src/content/dom/selectors.ts",
"retrieved_chunk": "// All the following are relative to COMPOSE_MODAL\nexport const COMPOSE_CANCEL_BUTTON = new Selector('[data-testid=\"composerCancelButton\"]');\nexport const COMPOSE_CONTENT_EDITABLE = new Selector('div.ProseMirror');\nexport const COMPOSE_LINK_CARD_BUTTON = new Selector('[data-testid=\"addLinkCardBtn\"]');\nexport const COMPOSE_PHOTO_BUTTON = new Selector('[data-testid=\"openGalleryBtn\"]');\nexport const SEARCH_BAR = new Selector('[data-testid=\"searchTextInput\"]'); // relative to FEED_CONTAINER\nexport const POST_ITEMS = new SelectorGroup([\n new Selector('[data-testid^=\"postThreadItem\"]', {exhaustAfter: 5000}),\n new Selector('[data-testid^=\"feedItem\"]', {exhaustAfter: 5000})\n]);",
"score": 27.379079125170634
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " Promise.all([\n ultimatelyFind(modal, COMPOSE_CANCEL_BUTTON),\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE)\n ]).then(([exitButton, contentEditable]) => {\n this.#exitButton = exitButton;\n this.#contentEditable = contentEditable;\n this.#eventKeeper.add(document, 'click', this.#onClick.bind(this));\n this.#eventKeeper.add(contentEditable, 'mousedown', this.#onPresumedSelect.bind(this));\n this.#eventKeeper.add(exitButton, 'click', () => this.#eventKeeper.cancelAll());\n });",
"score": 25.18966229654139
}
] | typescript | #modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => { |
import {IPausable} from '../../../interfaces';
import {TSelectorLike, ultimatelyFindAll} from '../../dom/utils';
import {LAST_CHILD, POST_ITEMS} from '../../dom/selectors';
import {Selector} from '../../dom/selector';
import {EventKeeper} from '../../utils/eventKeeper';
const LAG = 100;
const FOLLOWING_DATA = 'homeScreenFeedTabs-Following';
const WHATSHOT_DATA = 'homeScreenFeedTabs-What\'s hot';
const TAB_BUTTONS = new Selector('[data-testid="homeScreenFeedTabs"]', {exhaustAfter: LAG});
const FOLLOWING_FEED = new Selector('[data-testid="followingFeedPage"]');
const WHATSHOT_FEED = new Selector('[data-testid="whatshotFeedPage"]');
const getNextPost = (post: HTMLElement): HTMLElement | null => {
if (post.nextSibling) {
return post.nextSibling as HTMLElement;
} else {
const parent = post.parentElement;
if (parent && parent.nextSibling) {
return parent.nextSibling.firstChild as HTMLElement;
} else {
return null;
}
}
};
const getPreviousPost = (post: HTMLElement): HTMLElement | null => {
if (post.previousSibling) {
return post.previousSibling as HTMLElement;
} else {
const parent = post.parentElement;
if (parent && parent.previousSibling) {
return parent.previousSibling.lastChild as HTMLElement;
} else {
return null;
}
}
};
const isPostThreadDelimiter = (postCandidate: HTMLElement): boolean => {
return postCandidate.getAttribute('role') === 'link' && postCandidate.getAttribute('tabindex') === '0';
};
export class PostList implements IPausable {
readonly #container: HTMLElement;
readonly #mutationObserver: MutationObserver;
readonly #tabButtonEventKeeper = new EventKeeper();
#activeTabSelector: Selector = FOLLOWING_FEED;
#currentPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#mutationObserver = new MutationObserver(this.#onContainerMutation.bind(this));
this.#isPaused = startPaused;
if (!startPaused) this.start();
}
start(): void {
this.#isPaused = false;
}
pause(): void {
this.#isPaused = true;
}
getCurrentFeedTab(): Promise<Selector> {
return this.#isMainPage().then((isMainPage) => {
if (isMainPage) {
return this.#activeTabSelector.clone();
} else {
return Promise.reject('Not on main page');
}
});
}
setCurrentPost(element: HTMLElement): Promise<HTMLElement> {
return this.#resolveList().then((posts) => {
for (const post of posts) {
if (post === element || post.parentElement === element || post.contains(element)) {
this.#currentPost = post;
return this.#currentPost;
}
}
return Promise.reject('Element is not a post');
});
}
getNextPost(): Promise<HTMLElement> {
return this.#getNeighborPost(getNextPost);
}
getPreviousPost(): Promise<HTMLElement> {
return this.#getNeighborPost(getPreviousPost);
}
#getNeighborPost(retrieveFn: (post: HTMLElement) => HTMLElement | null): Promise<HTMLElement> {
if (this.#isPaused) return Promise.reject('PostList is paused');
return this.#resolveList().then((posts) => {
if (posts.length === 0) {
return Promise.reject('No posts found');
} else if (this.#currentPost) {
const neighborPost = retrieveFn(this.#currentPost);
if (neighborPost && (posts.includes(neighborPost) || isPostThreadDelimiter(neighborPost))) {
this.#currentPost = neighborPost;
} else if (!posts.includes(this.#currentPost)) {
this.#currentPost = posts[0];
}
} else {
this.#currentPost = posts[0];
}
return this.#currentPost;
});
}
#isMainPage(): Promise<boolean> {
return this.#findElements([TAB_BUTTONS]).then((tabButtonsList) => {
if (tabButtonsList.length !== 1) throw new Error('There should be exactly one tab button container');
this.#subscribeToTabButtons(tabButtonsList[0]);
return true;
}).catch(() => false);
}
#resolveList(): Promise<HTMLElement[]> {
return this.#isMainPage().then((isMainPage) => {
const prefixingSelectors = isMainPage ? [this.#activeTabSelector] : [];
| return this.#findElements([...prefixingSelectors, POST_ITEMS]).then((posts) => { |
if (posts.length === 0) {
return Promise.reject('No posts found');
} else {
return posts;
}
});
});
}
#subscribeToTabButtons(tabButtons: HTMLElement): void {
this.#tabButtonEventKeeper.cancelAll();
this.#tabButtonEventKeeper.add(tabButtons, 'click', this.#onTabButtonClick.bind(this));
}
#onContainerMutation(mutations: MutationRecord[]): void {
mutations.forEach((mutation) => {
if (mutation.target === this.#container) {
this.#currentPost = null;
}
});
}
#onTabButtonClick(event: MouseEvent): void {
const target = event.target as HTMLElement;
const data = target.getAttribute('data-testid');
if (data === FOLLOWING_DATA || target.querySelector(`[data-testid="${FOLLOWING_DATA}"]`)) {
if (this.#activeTabSelector !== FOLLOWING_FEED) this.#currentPost = null;
this.#activeTabSelector = FOLLOWING_FEED;
} else if (data === WHATSHOT_DATA || target.querySelector(`[data-testid="${WHATSHOT_DATA}"]`)) {
if (this.#activeTabSelector !== WHATSHOT_FEED) this.#currentPost = null;
this.#activeTabSelector = WHATSHOT_FEED;
}
}
#findElements(selectors: TSelectorLike[]): Promise<HTMLElement[]> {
return ultimatelyFindAll(this.#container, [LAST_CHILD, ...selectors]);
}
}
| src/content/watchers/helpers/postList.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/youtube.ts",
"retrieved_chunk": "const createYoutubePlayers = (container: HTMLElement): void => {\n ultimatelyFindAll(container, [POST_ITEMS, POST_ITEM_LINKS])\n .then((links) => injectYoutubePlayers(links as HTMLLinkElement[]))\n .catch(noop);\n};\nexport class YoutubeWatcher extends Watcher {\n readonly #container: HTMLElement;\n readonly #throttler: CallThrottler = new CallThrottler(THROTTLING_INTERVAL);\n readonly #observer: MutationObserver;\n constructor(container: HTMLElement) {",
"score": 19.680565241322675
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " #findSearchBar(): Promise<HTMLElement> {\n return ultimatelyFind(document.body, SEARCH_BAR);\n }\n async #loadNewPosts(): Promise<void> {\n try {\n const tab = await this.#postList.getCurrentFeedTab();\n const tabContainer = await ultimatelyFind(this.#container, tab);\n const newPostsButton = tabContainer.childNodes[1] as HTMLElement;\n if (newPostsButton && newPostsButton.nextSibling) {\n newPostsButton.click();",
"score": 19.472218270166838
},
{
"filename": "src/content/dom/utils.ts",
"retrieved_chunk": " const foundElements = await previousPromise;\n return findInElements(selector, foundElements);\n }, Promise.resolve([rootElement]));\n};\nexport const ultimatelyFind = (rootElement: HTMLElement, selectors: TSelectorOrArray): Promise<HTMLElement> => {\n return ultimatelyFindAll(rootElement, selectors).then((foundElements) => foundElements?.[0] ?? null);\n};",
"score": 17.787176912297035
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " const children = rootContainer.childNodes;\n const menuItems = children[1].childNodes;\n const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;\n if (newPostButton) {\n newPostButton.click();\n } else {\n tip('No new post button found');\n }\n }\n}",
"score": 16.70038182593357
},
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " if (this.#isPaused || event.ctrlKey || event.metaKey) return;\n if (PHOTO_KEYS.includes(event.key)) {\n Promise.all([\n ultimatelyFind(this.#container, LEFT_ARROW_BUTTON).catch(() => null),\n ultimatelyFind(this.#container, RIGHT_ARROW_BUTTON).catch(() => null)\n ]).then(([leftArrow, rightArrow]) => {\n if (event.key === 'ArrowLeft' && leftArrow !== null) {\n leftArrow.click();\n } else if (event.key === 'ArrowRight' && rightArrow !== null) {\n rightArrow.click();",
"score": 16.074510657228853
}
] | typescript | return this.#findElements([...prefixingSelectors, POST_ITEMS]).then((posts) => { |
import {IPausable} from '../../../interfaces';
import {TSelectorLike, ultimatelyFindAll} from '../../dom/utils';
import {LAST_CHILD, POST_ITEMS} from '../../dom/selectors';
import {Selector} from '../../dom/selector';
import {EventKeeper} from '../../utils/eventKeeper';
const LAG = 100;
const FOLLOWING_DATA = 'homeScreenFeedTabs-Following';
const WHATSHOT_DATA = 'homeScreenFeedTabs-What\'s hot';
const TAB_BUTTONS = new Selector('[data-testid="homeScreenFeedTabs"]', {exhaustAfter: LAG});
const FOLLOWING_FEED = new Selector('[data-testid="followingFeedPage"]');
const WHATSHOT_FEED = new Selector('[data-testid="whatshotFeedPage"]');
const getNextPost = (post: HTMLElement): HTMLElement | null => {
if (post.nextSibling) {
return post.nextSibling as HTMLElement;
} else {
const parent = post.parentElement;
if (parent && parent.nextSibling) {
return parent.nextSibling.firstChild as HTMLElement;
} else {
return null;
}
}
};
const getPreviousPost = (post: HTMLElement): HTMLElement | null => {
if (post.previousSibling) {
return post.previousSibling as HTMLElement;
} else {
const parent = post.parentElement;
if (parent && parent.previousSibling) {
return parent.previousSibling.lastChild as HTMLElement;
} else {
return null;
}
}
};
const isPostThreadDelimiter = (postCandidate: HTMLElement): boolean => {
return postCandidate.getAttribute('role') === 'link' && postCandidate.getAttribute('tabindex') === '0';
};
export class PostList implements IPausable {
readonly #container: HTMLElement;
readonly #mutationObserver: MutationObserver;
readonly #tabButtonEventKeeper = new EventKeeper();
#activeTabSelector: Selector = FOLLOWING_FEED;
#currentPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#mutationObserver = new MutationObserver(this.#onContainerMutation.bind(this));
this.#isPaused = startPaused;
if (!startPaused) this.start();
}
start(): void {
this.#isPaused = false;
}
pause(): void {
this.#isPaused = true;
}
getCurrentFeedTab(): Promise<Selector> {
return this.#isMainPage().then((isMainPage) => {
if (isMainPage) {
return this.#activeTabSelector.clone();
} else {
return Promise.reject('Not on main page');
}
});
}
setCurrentPost(element: HTMLElement): Promise<HTMLElement> {
return this.#resolveList().then((posts) => {
for (const post of posts) {
if (post === element || post.parentElement === element || post.contains(element)) {
this.#currentPost = post;
return this.#currentPost;
}
}
return Promise.reject('Element is not a post');
});
}
getNextPost(): Promise<HTMLElement> {
return this.#getNeighborPost(getNextPost);
}
getPreviousPost(): Promise<HTMLElement> {
return this.#getNeighborPost(getPreviousPost);
}
#getNeighborPost(retrieveFn: (post: HTMLElement) => HTMLElement | null): Promise<HTMLElement> {
if (this.#isPaused) return Promise.reject('PostList is paused');
return this.#resolveList().then((posts) => {
if (posts.length === 0) {
return Promise.reject('No posts found');
} else if (this.#currentPost) {
const neighborPost = retrieveFn(this.#currentPost);
if (neighborPost && (posts.includes(neighborPost) || isPostThreadDelimiter(neighborPost))) {
this.#currentPost = neighborPost;
} else if (!posts.includes(this.#currentPost)) {
this.#currentPost = posts[0];
}
} else {
this.#currentPost = posts[0];
}
return this.#currentPost;
});
}
#isMainPage(): Promise<boolean> {
return this.#findElements([TAB_BUTTONS]).then((tabButtonsList) => {
if (tabButtonsList.length !== 1) throw new Error('There should be exactly one tab button container');
this.#subscribeToTabButtons(tabButtonsList[0]);
return true;
}).catch(() => false);
}
#resolveList(): Promise<HTMLElement[]> {
return this.#isMainPage().then((isMainPage) => {
const prefixingSelectors = isMainPage ? [this.#activeTabSelector] : [];
return this.#findElements([...prefixingSelectors, POST_ITEMS]).then((posts) => {
if (posts.length === 0) {
return Promise.reject('No posts found');
} else {
return posts;
}
});
});
}
#subscribeToTabButtons(tabButtons: HTMLElement): void {
this.#tabButtonEventKeeper.cancelAll();
this.#tabButtonEventKeeper.add(tabButtons, 'click', this.#onTabButtonClick.bind(this));
}
#onContainerMutation(mutations: MutationRecord[]): void {
mutations.forEach((mutation) => {
if (mutation.target === this.#container) {
this.#currentPost = null;
}
});
}
#onTabButtonClick(event: MouseEvent): void {
const target = event.target as HTMLElement;
const data = target.getAttribute('data-testid');
if (data === FOLLOWING_DATA || target.querySelector(`[data-testid="${FOLLOWING_DATA}"]`)) {
if (this.#activeTabSelector !== FOLLOWING_FEED) this.#currentPost = null;
this.#activeTabSelector = FOLLOWING_FEED;
} else if (data === WHATSHOT_DATA || target.querySelector(`[data-testid="${WHATSHOT_DATA}"]`)) {
if (this.#activeTabSelector !== WHATSHOT_FEED) this.#currentPost = null;
this.#activeTabSelector = WHATSHOT_FEED;
}
}
| #findElements(selectors: TSelectorLike[]): Promise<HTMLElement[]> { |
return ultimatelyFindAll(this.#container, [LAST_CHILD, ...selectors]);
}
}
| src/content/watchers/helpers/postList.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": "const MISSING_POST_ERROR = 'No post is focused';\nconst REPLY_BUTTON_SELECTOR = '[data-testid=\"replyBtn\"]';\nconst REPOST_BUTTON_SELECTOR = '[data-testid=\"repostBtn\"]';\nconst LIKE_BUTTON_SELECTOR = '[data-testid=\"likeBtn\"]';\nexport class VimKeybindingsHandler implements IPausable {\n readonly #container: HTMLElement;\n readonly #postList: PostList;\n readonly #postClickEventKeeper = new EventKeeper();\n readonly #searchBarEventKeeper = new EventKeeper();\n #currentPost: HTMLElement | null = null;",
"score": 57.798031467967284
},
{
"filename": "src/content/dom/selectors.ts",
"retrieved_chunk": "// All the following are relative to COMPOSE_MODAL\nexport const COMPOSE_CANCEL_BUTTON = new Selector('[data-testid=\"composerCancelButton\"]');\nexport const COMPOSE_CONTENT_EDITABLE = new Selector('div.ProseMirror');\nexport const COMPOSE_LINK_CARD_BUTTON = new Selector('[data-testid=\"addLinkCardBtn\"]');\nexport const COMPOSE_PHOTO_BUTTON = new Selector('[data-testid=\"openGalleryBtn\"]');\nexport const SEARCH_BAR = new Selector('[data-testid=\"searchTextInput\"]'); // relative to FEED_CONTAINER\nexport const POST_ITEMS = new SelectorGroup([\n new Selector('[data-testid^=\"postThreadItem\"]', {exhaustAfter: 5000}),\n new Selector('[data-testid^=\"feedItem\"]', {exhaustAfter: 5000})\n]);",
"score": 52.06828622285098
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " event.preventDefault();\n const contentEditable = this.#contentEditable;\n let data = event.clipboardData.getData('text/plain');\n if (data.match(STAGING_URL_REGEX) !== null) {\n data = data.replace('https://staging.bsky.app/', 'https://bsky.app/');\n }\n contentEditable.focus();\n typeText(data);\n typeText(' '); // Add a space after the link for it to resolve as one\n // Wait for the text to be inserted into the contentEditable",
"score": 35.514850664074636
},
{
"filename": "src/content/hacks/emojiDataWrapper.ts",
"retrieved_chunk": "import * as data from '@emoji-mart/data';\n// This is done to make `data.categories` amenable to being rewritten by the emoji-mart library\nexport const emojiData = { ...data };",
"score": 34.28070336405524
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " setTimeout(() => {\n const lastChar = contentEditable.textContent?.slice(-1) ?? '';\n if (lastChar === ' ') backspace();\n if (data.match(URL_REGEX) !== null) {\n this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => {\n linkCardButton.click();\n });\n }\n }, 50);\n }",
"score": 27.985804945133978
}
] | typescript | #findElements(selectors: TSelectorLike[]): Promise<HTMLElement[]> { |
import { exportProject, exportWorkspaceData } from './exportData';
import fs from 'node:fs';
import { importWorkspaceData } from './importData';
import InternalDb from './db/InternalDb';
import { getActiveProjectId, getActiveWorkspace } from './db/localStorageUtils';
import { join } from 'node:path';
import importNewProjectButton from './ui/importNewProjectButton';
import projectDropdown from './ui/projectDropdown';
import alertModal from './ui/react/alertModal';
import renderModal from './ui/react/renderModal';
import injectStyles from './ui/injectStyles';
import autoExport from './autoExport';
// Inject UI elements.
// @ts-ignore
const currentVersion = (window.gitIntegrationInjectCounter || 0) + 1;
// @ts-ignore
window.gitIntegrationInjectCounter = currentVersion;
function doInject() {
// @ts-ignore
// Check if the window was reloaded. When it was reloaded the Global counter changed
if (window.gitIntegrationInjectCounter !== currentVersion) {
return;
}
injectStyles();
projectDropdown();
importNewProjectButton();
window.requestAnimationFrame(doInject);
}
window.requestAnimationFrame(doInject);
setInterval(autoExport, 5000);
module.exports.workspaceActions = [
{
label: 'Export workspace to Git',
icon: 'download',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot export workspace',
'You must first configure the project folder before exporting',
));
return;
}
| const data = await exportWorkspaceData(workspaceId); |
const targetFile = join(path, workspaceId + '.json');
fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));
},
},
{
label: 'Import workspace from Git',
icon: 'upload',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot import workspace',
'You must first configure the project folder before importing',
));
return;
}
const targetFile = join(path, workspaceId + '.json');
const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());
await importWorkspaceData(dataRaw);
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
},
},
];
| src/index.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 68.59697259322226
},
{
"filename": "src/ui/projectDropdown/importProjectButton.ts",
"retrieved_chunk": " const projectId = getActiveProjectId();\n if (!projectId) {\n await renderModal(alertModal('Internal error', 'No ProjectId found in LocalStorage'));\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot import Project',",
"score": 50.095786022032264
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " // \"Close\" the dropdown\n projectDropdown.remove();\n const projectId = getActiveProjectId();\n if (!projectId) {\n return;\n }\n const config = InternalDb.create();\n const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(",
"score": 47.882359145603225
},
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 47.36825917922187
},
{
"filename": "src/autoExport.ts",
"retrieved_chunk": " const projectId = getActiveProjectId();\n if (!projectId) {\n return;\n }\n const config = InternalDb.create();\n const { repositoryPath: path, autoExport } = config.getProject(projectId);\n if (!path || !autoExport || projectId === 'proj_default-project') {\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);",
"score": 38.09518083919524
}
] | typescript | const data = await exportWorkspaceData(workspaceId); |
import { exportProject, exportWorkspaceData } from './exportData';
import fs from 'node:fs';
import { importWorkspaceData } from './importData';
import InternalDb from './db/InternalDb';
import { getActiveProjectId, getActiveWorkspace } from './db/localStorageUtils';
import { join } from 'node:path';
import importNewProjectButton from './ui/importNewProjectButton';
import projectDropdown from './ui/projectDropdown';
import alertModal from './ui/react/alertModal';
import renderModal from './ui/react/renderModal';
import injectStyles from './ui/injectStyles';
import autoExport from './autoExport';
// Inject UI elements.
// @ts-ignore
const currentVersion = (window.gitIntegrationInjectCounter || 0) + 1;
// @ts-ignore
window.gitIntegrationInjectCounter = currentVersion;
function doInject() {
// @ts-ignore
// Check if the window was reloaded. When it was reloaded the Global counter changed
if (window.gitIntegrationInjectCounter !== currentVersion) {
return;
}
injectStyles();
projectDropdown();
importNewProjectButton();
window.requestAnimationFrame(doInject);
}
window.requestAnimationFrame(doInject);
setInterval(autoExport, 5000);
module.exports.workspaceActions = [
{
label: 'Export workspace to Git',
icon: 'download',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot export workspace',
'You must first configure the project folder before exporting',
));
return;
}
const data = await exportWorkspaceData(workspaceId);
const targetFile = join(path, workspaceId + '.json');
fs.writeFileSync(targetFile, JSON.stringify(data, null, 2));
},
},
{
label: 'Import workspace from Git',
icon: 'upload',
action: async () => {
const projectId = getActiveProjectId();
const workspaceId = getActiveWorkspace();
const config = InternalDb.create();
const path = config.getProjectPath(projectId);
if (!path || projectId === 'proj_default-project') {
await renderModal(alertModal(
'Cannot import workspace',
'You must first configure the project folder before importing',
));
return;
}
const targetFile = join(path, workspaceId + '.json');
const dataRaw = JSON.parse(fs.readFileSync(targetFile).toString());
await | importWorkspaceData(dataRaw); |
// Force Insomnia to read all data
// @ts-ignore
window.main.restart();
},
},
];
| src/index.ts | Its-treason-insomnia-plugin-git-integration-84a73e3 | [
{
"filename": "src/ui/projectDropdown/exportProjectButton.ts",
"retrieved_chunk": " 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');\n fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');",
"score": 55.415507026161045
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " const path = config.getProjectPath(projectId);\n if (!path || projectId === 'proj_default-project') {\n await renderModal(alertModal(\n 'Cannot export Project',\n 'You must first configure the project folder before exporting the project',\n ));\n return;\n }\n const [projectData, workspaces] = await exportProject(projectId);\n const targetFile = join(path, 'project.json');",
"score": 50.412870378107414
},
{
"filename": "src/importData.ts",
"retrieved_chunk": " // TODO: Validate this using Zod\n const project: GitSavedProject = JSON.parse(fs.readFileSync(projectFile).toString());\n // Read all the workspace data\n const workspaceData: GitSavedWorkspace[] = [];\n for (const workspaceId of project.workspaceIds) {\n const workspaceFile = join(path, workspaceId + '.json');\n // TODO: Validate this using Zod\n const workspace: GitSavedWorkspace = JSON.parse(fs.readFileSync(workspaceFile).toString());\n workspaceData.push(workspace);\n }",
"score": 34.44873814831774
},
{
"filename": "src/ui/projectDropdown/gitCommitButton.ts",
"retrieved_chunk": " fs.writeFileSync(targetFile, JSON.stringify(projectData, null, 2));\n await gitClient.add(targetFile);\n for (const workspace of workspaces) {\n const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n await gitClient.add(targetFile);\n }\n const status = await gitClient.status();\n if (status.staged.length === 0) {\n await renderModal(alertModal('No changes', 'There are no changes to commited'));",
"score": 32.25308015250449
},
{
"filename": "src/autoExport.ts",
"retrieved_chunk": " const targetFile = join(path, workspace.id + '.json');\n fs.writeFileSync(targetFile, JSON.stringify(workspace, null, 2));\n }\n}\nlet prevImport = '';\nasync function autoImportProject(path: string) {\n let project, workspaceData;\n try {\n [project, workspaceData] = readProjectData(path);\n } catch (e) {",
"score": 28.39118274054844
}
] | typescript | importWorkspaceData(dataRaw); |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
if (!(key in VIM_KEY_MAP)) return;
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
| case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage()); |
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost().then((p) => this.#highlightPost(p));
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
return ultimatelyFind(document.body, SEARCH_BAR);
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/vimActions.ts",
"retrieved_chunk": " return name.charAt(0).toUpperCase() + name.slice(1);\n};\nexport const generateHelpMessage = (): string => {\n const actions: { [key: string]: string[] } = {};\n for (const [key, action] of Object.entries(VIM_KEY_MAP)) {\n if (!(action in actions)) actions[action] = [];\n actions[action].push(`<span class=\"mono\">${key}</span>`);\n }\n const helpMessage = [];\n for (const [action, buttons] of Object.entries(actions)) {",
"score": 50.27951049731381
},
{
"filename": "src/content/watchers/helpers/vimActions.ts",
"retrieved_chunk": " SEARCH = 'search',\n SHOW_HELP = 'show_help'\n}\nexport const VIM_KEY_MAP = {\n '?': VIM_ACTIONS.SHOW_HELP,\n '/': VIM_ACTIONS.SEARCH,\n '.': VIM_ACTIONS.LOAD_NEW_POSTS,\n 'j': VIM_ACTIONS.NEXT_POST,\n 'k': VIM_ACTIONS.PREVIOUS_POST,\n 'l': VIM_ACTIONS.LIKE,",
"score": 32.71903798731165
},
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " if (this.#isPaused || event.ctrlKey || event.metaKey) return;\n if (PHOTO_KEYS.includes(event.key)) {\n Promise.all([\n ultimatelyFind(this.#container, LEFT_ARROW_BUTTON).catch(() => null),\n ultimatelyFind(this.#container, RIGHT_ARROW_BUTTON).catch(() => null)\n ]).then(([leftArrow, rightArrow]) => {\n if (event.key === 'ArrowLeft' && leftArrow !== null) {\n leftArrow.click();\n } else if (event.key === 'ArrowRight' && rightArrow !== null) {\n rightArrow.click();",
"score": 31.015915569050602
},
{
"filename": "src/content/browser/settingsManager.ts",
"retrieved_chunk": " this.#listeners[settingName]?.push(callback);\n if (settingName in this.settings) {\n callback(settingName, this.settings[settingName] as TSetting);\n }\n });\n }\n #onSettingsChange(newSettings: TSettings): void {\n this.settings = {...this.settings, ...newSettings};\n for (const [key, value] of Object.entries(newSettings)) {\n if (key in this.#listeners) {",
"score": 21.61096712359346
},
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " }\n });\n } else {\n this.#vimHandler.handle(event);\n }\n }\n}",
"score": 17.68073718737713
}
] | typescript | case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage()); |
import {COMPOSE_CONTENT_EDITABLE, COMPOSE_LINK_CARD_BUTTON} from '../dom/selectors';
import {log} from '../utils/logger';
import {typeText, backspace} from '../utils/text';
import {Pipeline} from './pipeline';
import {ultimatelyFind} from '../dom/utils';
import {EventKeeper} from '../utils/eventKeeper';
const STAGING_URL_REGEX = /.*(https:\/\/staging\.bsky\.app\/profile\/.*\/post\/.*\/?)$/;
const URL_REGEX = /.*(https:\/\/bsky\.app\/profile\/.*\/post\/.*\/?)$/;
export class QuotePostPipeline extends Pipeline {
#modal: HTMLElement | null;
#contentEditable: HTMLElement | null;
readonly #eventKeeper: EventKeeper;
constructor() {
super();
this.#modal = null;
this.#contentEditable = null;
this.#eventKeeper = new EventKeeper();
}
deploy(modal: HTMLElement): void {
if (this.#modal !== null) {
log('QuotePostPipeline is already deployed');
return;
}
this.#modal = modal;
ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {
this.#contentEditable = contentEditable;
this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});
});
}
terminate(): void {
if (this.#modal === null) {
log('QuotePostPipeline is not deployed');
return;
}
this.#eventKeeper.cancelAll();
this.#modal = this.#contentEditable = null;
}
onPaste(event: ClipboardEvent): void {
if (!event.clipboardData || !this.#contentEditable) return;
if (event.clipboardData.types.indexOf('text/plain') === -1) return;
event.preventDefault();
const contentEditable = this.#contentEditable;
let data = event.clipboardData.getData('text/plain');
if (data.match(STAGING_URL_REGEX) !== null) {
data = data.replace('https://staging.bsky.app/', 'https://bsky.app/');
}
contentEditable.focus();
typeText(data);
typeText(' '); // Add a space after the link for it to resolve as one
// Wait for the text to be inserted into the contentEditable
setTimeout(() => {
const lastChar = contentEditable.textContent?.slice(-1) ?? '';
if (lastChar === ' ') backspace();
if (data.match(URL_REGEX) !== null) {
| this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => { |
linkCardButton.click();
});
}
}, 50);
}
}
| src/content/pipelines/quotePost.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/hacks/emojiDataWrapper.ts",
"retrieved_chunk": "import * as data from '@emoji-mart/data';\n// This is done to make `data.categories` amenable to being rewritten by the emoji-mart library\nexport const emojiData = { ...data };",
"score": 32.25225268809419
},
{
"filename": "src/content/main.ts",
"retrieved_chunk": " log('Launched');\n}).catch(() => {\n setTimeout(() => {\n run().then(() => {\n log('Launched after the second attempt (1000ms delay)');\n }).catch((e) => {\n if (e === EXTENSION_DISABLED_CODE) return;\n console.error(`Failed to launch Bluesky Overhaul. Please, copy the error and report this issue: ${REPO_LINK}`);\n console.error(e);\n });",
"score": 28.302266057693913
},
{
"filename": "src/content/pipelines/emoji.ts",
"retrieved_chunk": " }\n this.#modal = modal;\n this.#picker = this.#createPicker();\n Promise.all([\n ultimatelyFind(modal, [COMPOSE_PHOTO_BUTTON]),\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE)\n ]).then(([photoButton, contentEditable]) => {\n this.#elems.photoButton = photoButton;\n this.#elems.contentEditable = contentEditable;\n this.#elems.emojiButton = createEmojiButton(this.#elems.photoButton);",
"score": 27.51480458109661
},
{
"filename": "src/content/dom/selectors.ts",
"retrieved_chunk": "// All the following are relative to COMPOSE_MODAL\nexport const COMPOSE_CANCEL_BUTTON = new Selector('[data-testid=\"composerCancelButton\"]');\nexport const COMPOSE_CONTENT_EDITABLE = new Selector('div.ProseMirror');\nexport const COMPOSE_LINK_CARD_BUTTON = new Selector('[data-testid=\"addLinkCardBtn\"]');\nexport const COMPOSE_PHOTO_BUTTON = new Selector('[data-testid=\"openGalleryBtn\"]');\nexport const SEARCH_BAR = new Selector('[data-testid=\"searchTextInput\"]'); // relative to FEED_CONTAINER\nexport const POST_ITEMS = new SelectorGroup([\n new Selector('[data-testid^=\"postThreadItem\"]', {exhaustAfter: 5000}),\n new Selector('[data-testid^=\"feedItem\"]', {exhaustAfter: 5000})\n]);",
"score": 27.379079125170634
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " Promise.all([\n ultimatelyFind(modal, COMPOSE_CANCEL_BUTTON),\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE)\n ]).then(([exitButton, contentEditable]) => {\n this.#exitButton = exitButton;\n this.#contentEditable = contentEditable;\n this.#eventKeeper.add(document, 'click', this.#onClick.bind(this));\n this.#eventKeeper.add(contentEditable, 'mousedown', this.#onPresumedSelect.bind(this));\n this.#eventKeeper.add(exitButton, 'click', () => this.#eventKeeper.cancelAll());\n });",
"score": 25.18966229654139
}
] | typescript | this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => { |
import {COMPOSE_CONTENT_EDITABLE, COMPOSE_LINK_CARD_BUTTON} from '../dom/selectors';
import {log} from '../utils/logger';
import {typeText, backspace} from '../utils/text';
import {Pipeline} from './pipeline';
import {ultimatelyFind} from '../dom/utils';
import {EventKeeper} from '../utils/eventKeeper';
const STAGING_URL_REGEX = /.*(https:\/\/staging\.bsky\.app\/profile\/.*\/post\/.*\/?)$/;
const URL_REGEX = /.*(https:\/\/bsky\.app\/profile\/.*\/post\/.*\/?)$/;
export class QuotePostPipeline extends Pipeline {
#modal: HTMLElement | null;
#contentEditable: HTMLElement | null;
readonly #eventKeeper: EventKeeper;
constructor() {
super();
this.#modal = null;
this.#contentEditable = null;
this.#eventKeeper = new EventKeeper();
}
deploy(modal: HTMLElement): void {
if (this.#modal !== null) {
log('QuotePostPipeline is already deployed');
return;
}
this.#modal = modal;
ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {
this.#contentEditable = contentEditable;
this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});
});
}
terminate(): void {
if (this.#modal === null) {
log('QuotePostPipeline is not deployed');
return;
}
this.#eventKeeper.cancelAll();
this.#modal = this.#contentEditable = null;
}
onPaste(event: ClipboardEvent): void {
if (!event.clipboardData || !this.#contentEditable) return;
if (event.clipboardData.types.indexOf('text/plain') === -1) return;
event.preventDefault();
const contentEditable = this.#contentEditable;
let data = event.clipboardData.getData('text/plain');
if (data.match(STAGING_URL_REGEX) !== null) {
data = data.replace('https://staging.bsky.app/', 'https://bsky.app/');
}
contentEditable.focus();
typeText(data);
typeText(' '); // Add a space after the link for it to resolve as one
// Wait for the text to be inserted into the contentEditable
setTimeout(() => {
const lastChar = contentEditable.textContent?.slice(-1) ?? '';
if ( | lastChar === ' ') backspace(); |
if (data.match(URL_REGEX) !== null) {
this.#modal && ultimatelyFind(this.#modal, COMPOSE_LINK_CARD_BUTTON).then((linkCardButton) => {
linkCardButton.click();
});
}
}, 50);
}
}
| src/content/pipelines/quotePost.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/hacks/emojiDataWrapper.ts",
"retrieved_chunk": "import * as data from '@emoji-mart/data';\n// This is done to make `data.categories` amenable to being rewritten by the emoji-mart library\nexport const emojiData = { ...data };",
"score": 37.66053013795193
},
{
"filename": "src/content/dom/selectors.ts",
"retrieved_chunk": "// All the following are relative to COMPOSE_MODAL\nexport const COMPOSE_CANCEL_BUTTON = new Selector('[data-testid=\"composerCancelButton\"]');\nexport const COMPOSE_CONTENT_EDITABLE = new Selector('div.ProseMirror');\nexport const COMPOSE_LINK_CARD_BUTTON = new Selector('[data-testid=\"addLinkCardBtn\"]');\nexport const COMPOSE_PHOTO_BUTTON = new Selector('[data-testid=\"openGalleryBtn\"]');\nexport const SEARCH_BAR = new Selector('[data-testid=\"searchTextInput\"]'); // relative to FEED_CONTAINER\nexport const POST_ITEMS = new SelectorGroup([\n new Selector('[data-testid^=\"postThreadItem\"]', {exhaustAfter: 5000}),\n new Selector('[data-testid^=\"feedItem\"]', {exhaustAfter: 5000})\n]);",
"score": 29.08513049160051
},
{
"filename": "src/content/bsky/api.ts",
"retrieved_chunk": " throw new LoginError();\n }\n};\nexport const fetchPost = async (agent: BskyAgent, username: string, postId: string): Promise<Post> => {\n const did = await agent.resolveHandle({ handle: username }).then((response) => response.data.did);\n const response = await agent.getPostThread({uri: `at://${did}/app.bsky.feed.post/${postId}`});\n return response.data.thread.post as Post;\n};",
"score": 26.771585829025792
},
{
"filename": "src/content/main.ts",
"retrieved_chunk": " log('Launched');\n}).catch(() => {\n setTimeout(() => {\n run().then(() => {\n log('Launched after the second attempt (1000ms delay)');\n }).catch((e) => {\n if (e === EXTENSION_DISABLED_CODE) return;\n console.error(`Failed to launch Bluesky Overhaul. Please, copy the error and report this issue: ${REPO_LINK}`);\n console.error(e);\n });",
"score": 25.878872228931456
},
{
"filename": "src/content/bsky/api.ts",
"retrieved_chunk": "import {Post} from '@atproto/api/dist/src/types/app/bsky/getPostThread';\nimport {BskyAgent} from '@atproto/api';\nexport class LoginError extends Error {}\nexport const getAgent = async (identifier: string, password: string): Promise<BskyAgent> => {\n const agent = new BskyAgent({service: 'https://bsky.social'});\n // TODO : cache session\n try {\n await agent.login({identifier, password});\n return agent;\n } catch {",
"score": 22.848692048128793
}
] | typescript | lastChar === ' ') backspace(); |
import '@webcomponents/custom-elements';
import {APP_SETTINGS} from '../shared/appSettings';
import {getSettingsManager} from './browser/settingsManager';
import {ultimatelyFind} from './dom/utils';
import {ROOT_CONTAINER, FEED_CONTAINER, MODAL_CONTAINER, COMPOSE_MODAL} from './dom/selectors';
import {CountersConcealer} from './watchers/countersConcealer';
import {KeydownWatcher} from './watchers/keydown';
import {PostDatetimeWatcher} from './watchers/postDatetime';
import {YoutubeWatcher} from './watchers/youtube';
import {PostModalPipeline} from './pipelines/postModal';
import {EmojiPipeline} from './pipelines/emoji';
import {QuotePostPipeline} from './pipelines/quotePost';
import {log} from './utils/logger';
import {PipelineManager} from './utils/pipelineManager';
const REPO_LINK = 'https://github.com/xenohunter/bluesky-overhaul';
const EXTENSION_DISABLED_CODE = 'EXTENSION_DISABLED';
const run = async (): Promise<void> => {
const settingsManager = await getSettingsManager();
if (settingsManager.get(APP_SETTINGS.BLUESKY_OVERHAUL_ENABLED) === false) {
return Promise.reject(EXTENSION_DISABLED_CODE);
}
return ultimatelyFind(document.body, ROOT_CONTAINER).then((rootContainer) => Promise.all([
Promise.resolve(rootContainer),
ultimatelyFind(rootContainer, FEED_CONTAINER),
ultimatelyFind(rootContainer, MODAL_CONTAINER)
]).then(([rootContainer, feedContainer, modalContainer]) => {
const countersConcealer = new CountersConcealer(document.body);
settingsManager.subscribe(countersConcealer);
countersConcealer.watch();
const keydownWatcher = new KeydownWatcher(rootContainer, feedContainer);
settingsManager.subscribe(keydownWatcher);
keydownWatcher.watch();
const postDatetimeWatcher = new PostDatetimeWatcher(feedContainer);
settingsManager.subscribe(postDatetimeWatcher);
postDatetimeWatcher.watch();
const youtubeWatcher = new YoutubeWatcher(feedContainer);
youtubeWatcher.watch();
const postModalPipeline = new PostModalPipeline(() => keydownWatcher.pause(), () => keydownWatcher.start());
const emojiPipeline = new EmojiPipeline(() => postModalPipeline.pause(), () => postModalPipeline.start());
const quotePostPipeline = new QuotePostPipeline();
const pipelineManager = new PipelineManager({
compose: [postModalPipeline, emojiPipeline, quotePostPipeline]
});
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.target === modalContainer) {
| const composePostModal = modalContainer.querySelector(COMPOSE_MODAL.selector) as HTMLElement | null; |
if (composePostModal !== null) {
pipelineManager.terminateExcept('compose');
pipelineManager.deploy('compose', composePostModal);
} else {
pipelineManager.terminateAll();
}
}
});
});
observer.observe(modalContainer, {childList: true, subtree: true});
}));
};
run().then(() => {
log('Launched');
}).catch(() => {
setTimeout(() => {
run().then(() => {
log('Launched after the second attempt (1000ms delay)');
}).catch((e) => {
if (e === EXTENSION_DISABLED_CODE) return;
console.error(`Failed to launch Bluesky Overhaul. Please, copy the error and report this issue: ${REPO_LINK}`);
console.error(e);
});
}, 1000);
});
| src/content/main.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " #subscribeToTabButtons(tabButtons: HTMLElement): void {\n this.#tabButtonEventKeeper.cancelAll();\n this.#tabButtonEventKeeper.add(tabButtons, 'click', this.#onTabButtonClick.bind(this));\n }\n #onContainerMutation(mutations: MutationRecord[]): void {\n mutations.forEach((mutation) => {\n if (mutation.target === this.#container) {\n this.#currentPost = null;\n }\n });",
"score": 36.105690707755734
},
{
"filename": "src/content/dom/utils.ts",
"retrieved_chunk": " const observer = new MutationObserver(() => {\n const foundElements = selector.retrieveFrom(elements);\n if (foundElements.length > 0) {\n observer.disconnect();\n resolve(foundElements);\n }\n });\n for (const element of elements) {\n observer.observe(element, {childList: true, subtree: true});\n }",
"score": 29.410521939935116
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " }\n start(): void {\n this.#paused = false;\n }\n pause(): void {\n this.#paused = true;\n }\n #onClick(event: MouseEvent): void {\n if (this.#paused) return;\n const target = event.target as HTMLElement;",
"score": 26.942222760715286
},
{
"filename": "src/content/watchers/youtube.ts",
"retrieved_chunk": " super();\n this.#container = container;\n this.#observer = new MutationObserver(() => {\n const currentLayout = this.#container.lastChild as HTMLElement;\n this.#throttler.call(() => createYoutubePlayers(currentLayout));\n });\n }\n watch(): void {\n const initialLayout = this.#container.lastChild as HTMLElement;\n this.#throttler.call(() => createYoutubePlayers(initialLayout));",
"score": 24.45399665664303
},
{
"filename": "src/content/dom/selectors.ts",
"retrieved_chunk": "// All the following are relative to COMPOSE_MODAL\nexport const COMPOSE_CANCEL_BUTTON = new Selector('[data-testid=\"composerCancelButton\"]');\nexport const COMPOSE_CONTENT_EDITABLE = new Selector('div.ProseMirror');\nexport const COMPOSE_LINK_CARD_BUTTON = new Selector('[data-testid=\"addLinkCardBtn\"]');\nexport const COMPOSE_PHOTO_BUTTON = new Selector('[data-testid=\"openGalleryBtn\"]');\nexport const SEARCH_BAR = new Selector('[data-testid=\"searchTextInput\"]'); // relative to FEED_CONTAINER\nexport const POST_ITEMS = new SelectorGroup([\n new Selector('[data-testid^=\"postThreadItem\"]', {exhaustAfter: 5000}),\n new Selector('[data-testid^=\"feedItem\"]', {exhaustAfter: 5000})\n]);",
"score": 24.23686297146905
}
] | typescript | const composePostModal = modalContainer.querySelector(COMPOSE_MODAL.selector) as HTMLElement | null; |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
if (!(key in VIM_KEY_MAP)) return;
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage());
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost() | .then((p) => this.#highlightPost(p)); |
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
return ultimatelyFind(document.body, SEARCH_BAR);
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/helpers/vimActions.ts",
"retrieved_chunk": " helpMessage.push(`<b>${toNormalText(action)}</b>: ${buttons.join(' ')}`);\n }\n return `\n <div class=\"bluesky-overhaul-help\">\n <h3>Bluesky Overhaul Vim Keybindings</h3>\n <p>${helpMessage.join('<br/>')}</p>\n <p>You can also Alt+Click to focus any specific post</p>\n </div>\n `;\n};",
"score": 20.346948244710525
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " this.#currentPost = post;\n return this.#currentPost;\n }\n }\n return Promise.reject('Element is not a post');\n });\n }\n getNextPost(): Promise<HTMLElement> {\n return this.#getNeighborPost(getNextPost);\n }",
"score": 19.598479809664813
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " getPreviousPost(): Promise<HTMLElement> {\n return this.#getNeighborPost(getPreviousPost);\n }\n #getNeighborPost(retrieveFn: (post: HTMLElement) => HTMLElement | null): Promise<HTMLElement> {\n if (this.#isPaused) return Promise.reject('PostList is paused');\n return this.#resolveList().then((posts) => {\n if (posts.length === 0) {\n return Promise.reject('No posts found');\n } else if (this.#currentPost) {\n const neighborPost = retrieveFn(this.#currentPost);",
"score": 9.599189552869547
},
{
"filename": "src/content/utils/notifications.ts",
"retrieved_chunk": "export const tip = throttle((message: string): void => {\n notifier.tip(message);\n});",
"score": 9.402740672875781
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " #subscribeToTabButtons(tabButtons: HTMLElement): void {\n this.#tabButtonEventKeeper.cancelAll();\n this.#tabButtonEventKeeper.add(tabButtons, 'click', this.#onTabButtonClick.bind(this));\n }\n #onContainerMutation(mutations: MutationRecord[]): void {\n mutations.forEach((mutation) => {\n if (mutation.target === this.#container) {\n this.#currentPost = null;\n }\n });",
"score": 8.650196613422048
}
] | typescript | .then((p) => this.#highlightPost(p)); |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
if (!(key in VIM_KEY_MAP)) return;
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage());
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost().then((p) => this.#highlightPost(p));
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
return ultimatelyFind(document.body, SEARCH_BAR);
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
| const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER); |
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/main.ts",
"retrieved_chunk": " }\n return ultimatelyFind(document.body, ROOT_CONTAINER).then((rootContainer) => Promise.all([\n Promise.resolve(rootContainer),\n ultimatelyFind(rootContainer, FEED_CONTAINER),\n ultimatelyFind(rootContainer, MODAL_CONTAINER)\n ]).then(([rootContainer, feedContainer, modalContainer]) => {\n const countersConcealer = new CountersConcealer(document.body);\n settingsManager.subscribe(countersConcealer);\n countersConcealer.watch();\n const keydownWatcher = new KeydownWatcher(rootContainer, feedContainer);",
"score": 30.56692711727327
},
{
"filename": "src/content/utils/notifications.ts",
"retrieved_chunk": "export const tip = throttle((message: string): void => {\n notifier.tip(message);\n});",
"score": 19.499998012011343
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " return this.#activeTabSelector.clone();\n } else {\n return Promise.reject('Not on main page');\n }\n });\n }\n setCurrentPost(element: HTMLElement): Promise<HTMLElement> {\n return this.#resolveList().then((posts) => {\n for (const post of posts) {\n if (post === element || post.parentElement === element || post.contains(element)) {",
"score": 17.54331946200802
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " const prefixingSelectors = isMainPage ? [this.#activeTabSelector] : [];\n return this.#findElements([...prefixingSelectors, POST_ITEMS]).then((posts) => {\n if (posts.length === 0) {\n return Promise.reject('No posts found');\n } else {\n return posts;\n }\n });\n });\n }",
"score": 15.89858808514599
},
{
"filename": "src/popup/blocks/Form.tsx",
"retrieved_chunk": "const BADGES: { [key in APP_SETTINGS]?: { type: BADGE_LEVEL, text: string } } = {\n [APP_SETTINGS.BLUESKY_OVERHAUL_ENABLED]: {type: BADGE_LEVEL.DANGER, text: 'page reload'},\n [APP_SETTINGS.HANDLE_VIM_KEYBINDINGS]: {type: BADGE_LEVEL.WARNING, text: 'experimental'},\n [APP_SETTINGS.SHOW_POST_DATETIME]: {type: BADGE_LEVEL.INFO, text: 'requires login'}\n};\nconst TIPS: { [key in APP_SETTINGS]?: string } = {\n [APP_SETTINGS.BLUESKY_OVERHAUL_ENABLED]: 'It will turn back on when the next release is ready',\n [APP_SETTINGS.HANDLE_VIM_KEYBINDINGS]: 'Press \"?\" while on Bluesky to see the list of keys',\n [APP_SETTINGS.SHOW_POST_DATETIME]: 'Enter your Bluesky credentials to enable this'\n};",
"score": 14.33855426132973
}
] | typescript | const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER); |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
if (!(key in VIM_KEY_MAP)) return;
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage());
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost().then((p) => this.#highlightPost(p));
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
| return ultimatelyFind(document.body, SEARCH_BAR); |
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " Promise.all([\n ultimatelyFind(modal, COMPOSE_CANCEL_BUTTON),\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE)\n ]).then(([exitButton, contentEditable]) => {\n this.#exitButton = exitButton;\n this.#contentEditable = contentEditable;\n this.#eventKeeper.add(document, 'click', this.#onClick.bind(this));\n this.#eventKeeper.add(contentEditable, 'mousedown', this.#onPresumedSelect.bind(this));\n this.#eventKeeper.add(exitButton, 'click', () => this.#eventKeeper.cancelAll());\n });",
"score": 22.711426850131573
},
{
"filename": "src/content/main.ts",
"retrieved_chunk": " }\n return ultimatelyFind(document.body, ROOT_CONTAINER).then((rootContainer) => Promise.all([\n Promise.resolve(rootContainer),\n ultimatelyFind(rootContainer, FEED_CONTAINER),\n ultimatelyFind(rootContainer, MODAL_CONTAINER)\n ]).then(([rootContainer, feedContainer, modalContainer]) => {\n const countersConcealer = new CountersConcealer(document.body);\n settingsManager.subscribe(countersConcealer);\n countersConcealer.watch();\n const keydownWatcher = new KeydownWatcher(rootContainer, feedContainer);",
"score": 18.272835656302583
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " log('QuotePostPipeline is already deployed');\n return;\n }\n this.#modal = modal;\n ultimatelyFind(modal, COMPOSE_CONTENT_EDITABLE).then((contentEditable) => {\n this.#contentEditable = contentEditable;\n this.#eventKeeper.add(contentEditable, 'paste', this.onPaste.bind(this), {capture: true});\n });\n }\n terminate(): void {",
"score": 14.727415158304414
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " #subscribeToTabButtons(tabButtons: HTMLElement): void {\n this.#tabButtonEventKeeper.cancelAll();\n this.#tabButtonEventKeeper.add(tabButtons, 'click', this.#onTabButtonClick.bind(this));\n }\n #onContainerMutation(mutations: MutationRecord[]): void {\n mutations.forEach((mutation) => {\n if (mutation.target === this.#container) {\n this.#currentPost = null;\n }\n });",
"score": 13.875551621960051
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " if (target?.tagName.toLowerCase() === 'button') return;\n if (!this.#modal?.contains(event.target as Node) && event.target !== this.#exitButton) {\n this.#eventKeeper.cancelAll();\n this.#exitButton?.click();\n }\n }\n #onPresumedSelect(): void {\n if (this.#paused) return;\n this.pause();\n document.addEventListener('mouseup', () => setTimeout(this.start.bind(this), 0), {once: true});",
"score": 11.394421178398545
}
] | typescript | return ultimatelyFind(document.body, SEARCH_BAR); |
import {IPausable} from '../../../interfaces';
import {ROOT_CONTAINER, SEARCH_BAR} from '../../dom/selectors';
import {EventKeeper} from '../../utils/eventKeeper';
import {noop} from '../../../shared/misc';
import {modal, tip} from '../../utils/notifications';
import {PostList} from './postList';
import {generateHelpMessage, VIM_ACTIONS, VIM_KEY_MAP} from './vimActions';
import {ultimatelyFind} from '../../dom/utils';
enum DIRECTION { NEXT, PREVIOUS }
const FOCUSED_POST_CLASS = 'bluesky-overhaul-focused-post';
const MISSING_POST_ERROR = 'No post is focused';
const REPLY_BUTTON_SELECTOR = '[data-testid="replyBtn"]';
const REPOST_BUTTON_SELECTOR = '[data-testid="repostBtn"]';
const LIKE_BUTTON_SELECTOR = '[data-testid="likeBtn"]';
export class VimKeybindingsHandler implements IPausable {
readonly #container: HTMLElement;
readonly #postList: PostList;
readonly #postClickEventKeeper = new EventKeeper();
readonly #searchBarEventKeeper = new EventKeeper();
#currentPost: HTMLElement | null = null;
#stashedPost: HTMLElement | null = null;
#isPaused: boolean;
constructor(targetContainer: HTMLElement, startPaused = true) {
this.#container = targetContainer;
this.#postList = new PostList(targetContainer, startPaused);
this.#isPaused = startPaused;
}
start(): void {
if (!this.#isPaused) return;
this.#postList.start();
this.#postClickEventKeeper.add(this.#container, 'click', this.#onPostAltClick.bind(this));
this.#blurSearchBar();
this.#isPaused = false;
}
pause(): void {
if (this.#isPaused) return;
this.#postList.pause();
this.#postClickEventKeeper.cancelAll();
this.#searchBarEventKeeper.cancelAll();
this.#removeHighlight();
this.#isPaused = true;
}
handle(event: KeyboardEvent): void {
if (this.#isPaused) return;
event.preventDefault();
const key = event.key;
| if (!(key in VIM_KEY_MAP)) return; |
const action = VIM_KEY_MAP[key as keyof typeof VIM_KEY_MAP];
switch (action) {
case VIM_ACTIONS.SHOW_HELP:
modal(generateHelpMessage());
break;
case VIM_ACTIONS.SEARCH:
this.#focusSearchBar();
break;
case VIM_ACTIONS.LOAD_NEW_POSTS:
this.#loadNewPosts();
break;
case VIM_ACTIONS.NEXT_POST:
this.#selectPost(DIRECTION.NEXT);
break;
case VIM_ACTIONS.PREVIOUS_POST:
this.#selectPost(DIRECTION.PREVIOUS);
break;
case VIM_ACTIONS.LIKE:
this.#likePost();
break;
case VIM_ACTIONS.CREATE_POST:
this.#newPost();
break;
case VIM_ACTIONS.EXPAND_IMAGE:
this.#expandImage();
break;
case VIM_ACTIONS.REPLY:
this.#replyToPost();
break;
case VIM_ACTIONS.REPOST:
this.#repostPost();
break;
case VIM_ACTIONS.OPEN_POST:
this.#currentPost?.click();
break;
default:
tip(`Action "${action}" is not implemented yet`);
}
}
#selectPost(direction: DIRECTION): void {
if (direction === DIRECTION.NEXT) {
this.#postList.getNextPost().then((p) => this.#highlightPost(p));
} else {
this.#postList.getPreviousPost().then((p) => this.#highlightPost(p));
}
}
#replyToPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const reply = this.#currentPost.querySelector(REPLY_BUTTON_SELECTOR) as HTMLElement;
reply?.click();
}
#repostPost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const repost = this.#currentPost.querySelector(REPOST_BUTTON_SELECTOR) as HTMLElement;
repost?.click();
}
#likePost(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const like = this.#currentPost.querySelector(LIKE_BUTTON_SELECTOR) as HTMLElement;
like?.click();
}
#expandImage(): void {
if (!this.#currentPost) return tip(MISSING_POST_ERROR);
const imageContainer = this.#currentPost.querySelector('div.expo-image-container') as HTMLElement;
imageContainer?.click();
}
#onPostAltClick(event: MouseEvent): void {
if (this.#isPaused || !event.altKey) return;
event.preventDefault();
this.#postList.setCurrentPost(event.target as HTMLElement).then((p) => this.#highlightPost(p)).catch(noop);
}
#highlightPost(post: HTMLElement): void {
if (post === this.#currentPost) return;
this.#removeHighlight();
this.#stashedPost = null;
this.#currentPost = post;
this.#currentPost.classList.add(FOCUSED_POST_CLASS);
this.#currentPost.scrollIntoView({block: 'center', behavior: 'smooth'});
}
#removeHighlight(): void {
this.#stashedPost = this.#currentPost;
this.#currentPost?.classList.remove(FOCUSED_POST_CLASS);
this.#currentPost = null;
}
#focusSearchBar(): void {
this.#removeHighlight();
this.#findSearchBar().then((searchBar) => {
this.#searchBarEventKeeper.cancelAll();
searchBar.focus();
this.#searchBarEventKeeper.add(searchBar, 'blur', this.#blurSearchBar.bind(this));
this.#searchBarEventKeeper.add(searchBar, 'keydown', (event: KeyboardEvent) => {
if (event.key === 'Escape') searchBar.blur();
});
}).catch(() => tip('Search bar not found'));
}
#blurSearchBar(): void {
this.#searchBarEventKeeper.cancelAll();
this.#findSearchBar().then((searchBar) => {
searchBar.blur();
this.#stashedPost && this.#highlightPost(this.#stashedPost);
this.#searchBarEventKeeper.add(searchBar, 'focus', this.#focusSearchBar.bind(this));
});
}
#findSearchBar(): Promise<HTMLElement> {
return ultimatelyFind(document.body, SEARCH_BAR);
}
async #loadNewPosts(): Promise<void> {
try {
const tab = await this.#postList.getCurrentFeedTab();
const tabContainer = await ultimatelyFind(this.#container, tab);
const newPostsButton = tabContainer.childNodes[1] as HTMLElement;
if (newPostsButton && newPostsButton.nextSibling) {
newPostsButton.click();
this.#container.scrollIntoView({block: 'start', behavior: 'smooth'});
} else {
tip('No new posts to load');
}
} catch {
tip('You are not on the feed page');
}
}
async #newPost(): Promise<void> {
const rootContainer = await ultimatelyFind(document.body, ROOT_CONTAINER);
const children = rootContainer.childNodes;
const menuItems = children[1].childNodes;
const newPostButton = menuItems[menuItems.length - 1] as HTMLElement;
if (newPostButton) {
newPostButton.click();
} else {
tip('No new post button found');
}
}
}
| src/content/watchers/helpers/vimKeybindings.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/watchers/keydown.ts",
"retrieved_chunk": " if (this.#isPaused || event.ctrlKey || event.metaKey) return;\n if (PHOTO_KEYS.includes(event.key)) {\n Promise.all([\n ultimatelyFind(this.#container, LEFT_ARROW_BUTTON).catch(() => null),\n ultimatelyFind(this.#container, RIGHT_ARROW_BUTTON).catch(() => null)\n ]).then(([leftArrow, rightArrow]) => {\n if (event.key === 'ArrowLeft' && leftArrow !== null) {\n leftArrow.click();\n } else if (event.key === 'ArrowRight' && rightArrow !== null) {\n rightArrow.click();",
"score": 31.135221365911544
},
{
"filename": "src/content/pipelines/quotePost.ts",
"retrieved_chunk": " if (this.#modal === null) {\n log('QuotePostPipeline is not deployed');\n return;\n }\n this.#eventKeeper.cancelAll();\n this.#modal = this.#contentEditable = null;\n }\n onPaste(event: ClipboardEvent): void {\n if (!event.clipboardData || !this.#contentEditable) return;\n if (event.clipboardData.types.indexOf('text/plain') === -1) return;",
"score": 21.06137976921416
},
{
"filename": "src/content/utils/eventKeeper.ts",
"retrieved_chunk": " cancelAll(): void {\n for (const {element, event, listener, options} of this.#events) {\n try {\n element.removeEventListener(event, listener as TEventListener<Event>, options);\n } catch (e) {\n noop();\n }\n }\n this.#events = [];\n }",
"score": 20.303540993550968
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " if (target?.tagName.toLowerCase() === 'button') return;\n if (!this.#modal?.contains(event.target as Node) && event.target !== this.#exitButton) {\n this.#eventKeeper.cancelAll();\n this.#exitButton?.click();\n }\n }\n #onPresumedSelect(): void {\n if (this.#paused) return;\n this.pause();\n document.addEventListener('mouseup', () => setTimeout(this.start.bind(this), 0), {once: true});",
"score": 20.212419481755873
},
{
"filename": "src/content/watchers/helpers/vimActions.ts",
"retrieved_chunk": " return name.charAt(0).toUpperCase() + name.slice(1);\n};\nexport const generateHelpMessage = (): string => {\n const actions: { [key: string]: string[] } = {};\n for (const [key, action] of Object.entries(VIM_KEY_MAP)) {\n if (!(action in actions)) actions[action] = [];\n actions[action].push(`<span class=\"mono\">${key}</span>`);\n }\n const helpMessage = [];\n for (const [action, buttons] of Object.entries(actions)) {",
"score": 19.301471296076752
}
] | typescript | if (!(key in VIM_KEY_MAP)) return; |
import { createPopper } from '@popperjs/core';
import {TSetting, TSettings} from '../../types';
import {APP_SETTINGS} from '../../shared/appSettings';
import {ISettingsSubscriber} from '../../interfaces';
import {Watcher} from './watcher';
import {getSettingsManager} from '../browser/settingsManager';
import {getAgent, fetchPost, LoginError} from '../bsky/api';
import {alert} from '../utils/notifications';
const DEFAULT_SETTINGS: Partial<TSettings> = {
[APP_SETTINGS.SHOW_POST_DATETIME]: false,
[APP_SETTINGS.BSKY_IDENTIFIER]: '',
[APP_SETTINGS.BSKY_PASSWORD]: ''
};
type PostUrl = {
username: string;
postId: string;
};
const POST_HREF_REGEX = /profile\/(.+)\/post\/([a-zA-Z0-9]+)$/;
const DATETIME_MARKER = 'data-bluesky-overhaul-datetime';
const getCredentials = async (): Promise<[string, string]> => {
const settingsManager = await getSettingsManager();
return await Promise.all([
settingsManager.get(APP_SETTINGS.BSKY_IDENTIFIER) as string,
settingsManager.get(APP_SETTINGS.BSKY_PASSWORD) as string
]);
};
const parsePostUrl = (url: string | null): PostUrl => {
if (!url) throw new Error('Missing post URL');
const match = url.match(POST_HREF_REGEX);
if (!match) throw new Error('Invalid post URL');
return {username: match[1], postId: match[2]};
};
const parsePostDatetime = (datetime: string): string => {
const date = new Date(datetime);
return date.toLocaleString('en-US', {
month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'
});
};
const createDatetimeTooltip = (datetime: string): HTMLElement => {
const tooltip = document.createElement('div');
tooltip.role = 'tooltip';
tooltip.className = 'bluesky-overhaul-tooltip';
tooltip.textContent = datetime;
return tooltip;
};
export class | PostDatetimeWatcher extends Watcher implements ISettingsSubscriber { |
#container: HTMLElement;
#enabled: boolean;
constructor(container: HTMLElement) {
super();
this.#container = container;
this.#enabled = DEFAULT_SETTINGS[APP_SETTINGS.SHOW_POST_DATETIME] as boolean;
}
watch(): void {
this.#container.addEventListener('mouseover', this.#handleMouseOver.bind(this));
}
onSettingChange(name: APP_SETTINGS, value: TSetting): void {
if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name "${name}"`);
if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value "${value}" for "${name}"`);
if (name === APP_SETTINGS.SHOW_POST_DATETIME) {
this.#enabled = value as boolean;
}
}
get SETTINGS(): APP_SETTINGS[] {
return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];
}
async #handleMouseOver(event: MouseEvent): Promise<void> {
if (!this.#enabled) return;
const target = event.target as HTMLElement;
if (target.tagName.toLowerCase() !== 'a') return;
let datetime = target.getAttribute(DATETIME_MARKER);
if (!datetime) {
try {
const {username, postId} = parsePostUrl(target.getAttribute('href'));
if (username && postId) {
const [identifier, password] = await getCredentials();
try {
const agent = await getAgent(identifier, password);
const post = await fetchPost(agent, username, postId);
datetime = parsePostDatetime(post.indexedAt);
target.setAttribute(DATETIME_MARKER, datetime);
} catch (error) {
if (error instanceof LoginError) alert('Login failed: wrong identifier or password');
return;
}
} else {
return;
}
} catch {
return;
}
}
const tooltip = createDatetimeTooltip(datetime);
document.body.appendChild(tooltip);
const instance = createPopper(target, tooltip, {
placement: 'top'
});
target.addEventListener('mouseleave', () => {
instance.destroy();
tooltip.remove();
}, {once: true});
}
}
| src/content/watchers/postDatetime.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/popup/components/Checkbox.tsx",
"retrieved_chunk": " <label>\n <input type=\"checkbox\" checked={checked} onChange={onChange}/>\n <span>{text}</span>\n {badge && <Badge text={badge.text} type={badge.type}/>}\n {tooltip && <Tip text={tooltip}/>}\n </label>\n </div>\n </div>\n </div>\n );",
"score": 43.22979561934985
},
{
"filename": "src/popup/components/Checkbox.tsx",
"retrieved_chunk": "export default function Checkbox({value, text, badge, tooltip, callback}: CheckboxProps): JSX.Element {\n const [checked, setChecked] = useState(value);\n const onChange = (event: React.ChangeEvent<HTMLInputElement>): void => {\n setChecked(event.target.checked);\n callback(event.target.checked);\n };\n return (\n <div className=\"form-group\">\n <div className=\"col-sm-offset-2 col-sm-10\">\n <div className=\"checkbox\">",
"score": 33.254814003242075
},
{
"filename": "src/content/watchers/countersConcealer.ts",
"retrieved_chunk": "const HIDE_FOLLOWERS_CLASS = 'bluesky-overhaul-hide-followers';\nconst HIDE_FOLLOWING_CLASS = 'bluesky-overhaul-hide-following';\nconst HIDE_POSTS_CLASS = 'bluesky-overhaul-hide-posts';\nexport class CountersConcealer extends Watcher implements ISettingsSubscriber {\n #container: HTMLElement;\n constructor(documentBody: HTMLElement) {\n super();\n this.#container = documentBody;\n }\n watch(): void {",
"score": 29.23943626249612
},
{
"filename": "src/popup/components/Checkbox.tsx",
"retrieved_chunk": "import React, {useState} from 'react';\nimport Badge, {BADGE_LEVEL} from './Badge';\nimport Tip from './Tip';\ntype CheckboxProps = {\n value: boolean;\n text: string;\n badge?: { text: string, type: BADGE_LEVEL };\n tooltip?: string;\n callback: (value: boolean) => void;\n};",
"score": 29.075005335008598
},
{
"filename": "src/popup/blocks/Form.tsx",
"retrieved_chunk": " return <Checkbox\n key={name}\n value={value as boolean} // TODO : fix this\n text={nameToText(name)}\n badge={BADGES[name]}\n tooltip={TIPS[name]}\n callback={(newValue) => onChange(name, newValue)}\n />;\n }\n })}",
"score": 28.892236589866968
}
] | typescript | PostDatetimeWatcher extends Watcher implements ISettingsSubscriber { |
import { createPopper } from '@popperjs/core';
import {TSetting, TSettings} from '../../types';
import {APP_SETTINGS} from '../../shared/appSettings';
import {ISettingsSubscriber} from '../../interfaces';
import {Watcher} from './watcher';
import {getSettingsManager} from '../browser/settingsManager';
import {getAgent, fetchPost, LoginError} from '../bsky/api';
import {alert} from '../utils/notifications';
const DEFAULT_SETTINGS: Partial<TSettings> = {
[APP_SETTINGS.SHOW_POST_DATETIME]: false,
[APP_SETTINGS.BSKY_IDENTIFIER]: '',
[APP_SETTINGS.BSKY_PASSWORD]: ''
};
type PostUrl = {
username: string;
postId: string;
};
const POST_HREF_REGEX = /profile\/(.+)\/post\/([a-zA-Z0-9]+)$/;
const DATETIME_MARKER = 'data-bluesky-overhaul-datetime';
const getCredentials = async (): Promise<[string, string]> => {
const settingsManager = await getSettingsManager();
return await Promise.all([
settingsManager.get(APP_SETTINGS.BSKY_IDENTIFIER) as string,
settingsManager.get(APP_SETTINGS.BSKY_PASSWORD) as string
]);
};
const parsePostUrl = (url: string | null): PostUrl => {
if (!url) throw new Error('Missing post URL');
const match = url.match(POST_HREF_REGEX);
if (!match) throw new Error('Invalid post URL');
return {username: match[1], postId: match[2]};
};
const parsePostDatetime = (datetime: string): string => {
const date = new Date(datetime);
return date.toLocaleString('en-US', {
month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'
});
};
const createDatetimeTooltip = (datetime: string): HTMLElement => {
const tooltip = document.createElement('div');
tooltip.role = 'tooltip';
tooltip.className = 'bluesky-overhaul-tooltip';
tooltip.textContent = datetime;
return tooltip;
};
export class PostDatetimeWatcher extends Watcher implements ISettingsSubscriber {
#container: HTMLElement;
#enabled: boolean;
constructor(container: HTMLElement) {
super();
this.#container = container;
this.#enabled = DEFAULT_SETTINGS[APP_SETTINGS.SHOW_POST_DATETIME] as boolean;
}
watch(): void {
this.#container.addEventListener('mouseover', this.#handleMouseOver.bind(this));
}
onSettingChange(name: APP_SETTINGS, value: TSetting): void {
if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name "${name}"`);
if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value "${value}" for "${name}"`);
if (name === APP_SETTINGS.SHOW_POST_DATETIME) {
this.#enabled = value as boolean;
}
}
get SETTINGS(): APP_SETTINGS[] {
return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];
}
async #handleMouseOver(event: MouseEvent): Promise<void> {
if (!this.#enabled) return;
const target = event.target as HTMLElement;
if (target.tagName.toLowerCase() !== 'a') return;
let datetime = target.getAttribute(DATETIME_MARKER);
if (!datetime) {
try {
const {username, postId} = parsePostUrl(target.getAttribute('href'));
if (username && postId) {
const [identifier, password] = await getCredentials();
try {
const agent = await getAgent(identifier, password);
const post = | await fetchPost(agent, username, postId); |
datetime = parsePostDatetime(post.indexedAt);
target.setAttribute(DATETIME_MARKER, datetime);
} catch (error) {
if (error instanceof LoginError) alert('Login failed: wrong identifier or password');
return;
}
} else {
return;
}
} catch {
return;
}
}
const tooltip = createDatetimeTooltip(datetime);
document.body.appendChild(tooltip);
const instance = createPopper(target, tooltip, {
placement: 'top'
});
target.addEventListener('mouseleave', () => {
instance.destroy();
tooltip.remove();
}, {once: true});
}
}
| src/content/watchers/postDatetime.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/bsky/api.ts",
"retrieved_chunk": " throw new LoginError();\n }\n};\nexport const fetchPost = async (agent: BskyAgent, username: string, postId: string): Promise<Post> => {\n const did = await agent.resolveHandle({ handle: username }).then((response) => response.data.did);\n const response = await agent.getPostThread({uri: `at://${did}/app.bsky.feed.post/${postId}`});\n return response.data.thread.post as Post;\n};",
"score": 70.7168855839968
},
{
"filename": "src/content/bsky/api.ts",
"retrieved_chunk": "import {Post} from '@atproto/api/dist/src/types/app/bsky/getPostThread';\nimport {BskyAgent} from '@atproto/api';\nexport class LoginError extends Error {}\nexport const getAgent = async (identifier: string, password: string): Promise<BskyAgent> => {\n const agent = new BskyAgent({service: 'https://bsky.social'});\n // TODO : cache session\n try {\n await agent.login({identifier, password});\n return agent;\n } catch {",
"score": 51.45892981272463
},
{
"filename": "src/shared/appSettings.ts",
"retrieved_chunk": "import {TSettings} from '../types';\nexport enum APP_SETTINGS {\n BLUESKY_OVERHAUL_ENABLED = 'bluesky-overhaul-enabled',\n HANDLE_VIM_KEYBINDINGS = 'vim-keybindings',\n HIDE_FOLLOWERS_COUNT = 'hide-followers-count',\n HIDE_FOLLOWING_COUNT = 'hide-following-count',\n HIDE_POSTS_COUNT = 'hide-posts-count',\n SHOW_POST_DATETIME = 'show-post-datetime',\n BSKY_IDENTIFIER = 'bsky-identifier',\n BSKY_PASSWORD = 'bsky-password'",
"score": 27.060168465194216
},
{
"filename": "src/content/watchers/helpers/vimKeybindings.ts",
"retrieved_chunk": " #findSearchBar(): Promise<HTMLElement> {\n return ultimatelyFind(document.body, SEARCH_BAR);\n }\n async #loadNewPosts(): Promise<void> {\n try {\n const tab = await this.#postList.getCurrentFeedTab();\n const tabContainer = await ultimatelyFind(this.#container, tab);\n const newPostsButton = tabContainer.childNodes[1] as HTMLElement;\n if (newPostsButton && newPostsButton.nextSibling) {\n newPostsButton.click();",
"score": 22.216772355254772
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " }\n #onTabButtonClick(event: MouseEvent): void {\n const target = event.target as HTMLElement;\n const data = target.getAttribute('data-testid');\n if (data === FOLLOWING_DATA || target.querySelector(`[data-testid=\"${FOLLOWING_DATA}\"]`)) {\n if (this.#activeTabSelector !== FOLLOWING_FEED) this.#currentPost = null;\n this.#activeTabSelector = FOLLOWING_FEED;\n } else if (data === WHATSHOT_DATA || target.querySelector(`[data-testid=\"${WHATSHOT_DATA}\"]`)) {\n if (this.#activeTabSelector !== WHATSHOT_FEED) this.#currentPost = null;\n this.#activeTabSelector = WHATSHOT_FEED;",
"score": 20.792947826936967
}
] | typescript | await fetchPost(agent, username, postId); |
import { createPopper } from '@popperjs/core';
import {TSetting, TSettings} from '../../types';
import {APP_SETTINGS} from '../../shared/appSettings';
import {ISettingsSubscriber} from '../../interfaces';
import {Watcher} from './watcher';
import {getSettingsManager} from '../browser/settingsManager';
import {getAgent, fetchPost, LoginError} from '../bsky/api';
import {alert} from '../utils/notifications';
const DEFAULT_SETTINGS: Partial<TSettings> = {
[APP_SETTINGS.SHOW_POST_DATETIME]: false,
[APP_SETTINGS.BSKY_IDENTIFIER]: '',
[APP_SETTINGS.BSKY_PASSWORD]: ''
};
type PostUrl = {
username: string;
postId: string;
};
const POST_HREF_REGEX = /profile\/(.+)\/post\/([a-zA-Z0-9]+)$/;
const DATETIME_MARKER = 'data-bluesky-overhaul-datetime';
const getCredentials = async (): Promise<[string, string]> => {
const settingsManager = await getSettingsManager();
return await Promise.all([
settingsManager.get(APP_SETTINGS.BSKY_IDENTIFIER) as string,
settingsManager.get(APP_SETTINGS.BSKY_PASSWORD) as string
]);
};
const parsePostUrl = (url: string | null): PostUrl => {
if (!url) throw new Error('Missing post URL');
const match = url.match(POST_HREF_REGEX);
if (!match) throw new Error('Invalid post URL');
return {username: match[1], postId: match[2]};
};
const parsePostDatetime = (datetime: string): string => {
const date = new Date(datetime);
return date.toLocaleString('en-US', {
month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric'
});
};
const createDatetimeTooltip = (datetime: string): HTMLElement => {
const tooltip = document.createElement('div');
tooltip.role = 'tooltip';
tooltip.className = 'bluesky-overhaul-tooltip';
tooltip.textContent = datetime;
return tooltip;
};
export class PostDatetimeWatcher extends Watcher implements ISettingsSubscriber {
#container: HTMLElement;
#enabled: boolean;
constructor(container: HTMLElement) {
super();
this.#container = container;
this.#enabled = DEFAULT_SETTINGS[APP_SETTINGS.SHOW_POST_DATETIME] as boolean;
}
watch(): void {
this.#container.addEventListener('mouseover', this.#handleMouseOver.bind(this));
}
onSettingChange(name: APP_SETTINGS, value: TSetting): void {
if (!this.SETTINGS.includes(name)) throw new Error(`Unknown setting name "${name}"`);
if (typeof value !== typeof DEFAULT_SETTINGS[name]) throw new Error(`Invalid value "${value}" for "${name}"`);
if (name === APP_SETTINGS.SHOW_POST_DATETIME) {
this.#enabled = value as boolean;
}
}
get SETTINGS(): APP_SETTINGS[] {
return Object.keys(DEFAULT_SETTINGS) as APP_SETTINGS[];
}
async #handleMouseOver(event: MouseEvent): Promise<void> {
if (!this.#enabled) return;
const target = event.target as HTMLElement;
if (target.tagName.toLowerCase() !== 'a') return;
let datetime = target.getAttribute(DATETIME_MARKER);
if (!datetime) {
try {
const {username, postId} = parsePostUrl(target.getAttribute('href'));
if (username && postId) {
const [identifier, password] = await getCredentials();
try {
| const agent = await getAgent(identifier, password); |
const post = await fetchPost(agent, username, postId);
datetime = parsePostDatetime(post.indexedAt);
target.setAttribute(DATETIME_MARKER, datetime);
} catch (error) {
if (error instanceof LoginError) alert('Login failed: wrong identifier or password');
return;
}
} else {
return;
}
} catch {
return;
}
}
const tooltip = createDatetimeTooltip(datetime);
document.body.appendChild(tooltip);
const instance = createPopper(target, tooltip, {
placement: 'top'
});
target.addEventListener('mouseleave', () => {
instance.destroy();
tooltip.remove();
}, {once: true});
}
}
| src/content/watchers/postDatetime.ts | xenohunter-bluesky-overhaul-ec599a6 | [
{
"filename": "src/content/bsky/api.ts",
"retrieved_chunk": " throw new LoginError();\n }\n};\nexport const fetchPost = async (agent: BskyAgent, username: string, postId: string): Promise<Post> => {\n const did = await agent.resolveHandle({ handle: username }).then((response) => response.data.did);\n const response = await agent.getPostThread({uri: `at://${did}/app.bsky.feed.post/${postId}`});\n return response.data.thread.post as Post;\n};",
"score": 43.81296191686805
},
{
"filename": "src/content/bsky/api.ts",
"retrieved_chunk": "import {Post} from '@atproto/api/dist/src/types/app/bsky/getPostThread';\nimport {BskyAgent} from '@atproto/api';\nexport class LoginError extends Error {}\nexport const getAgent = async (identifier: string, password: string): Promise<BskyAgent> => {\n const agent = new BskyAgent({service: 'https://bsky.social'});\n // TODO : cache session\n try {\n await agent.login({identifier, password});\n return agent;\n } catch {",
"score": 43.61412967793552
},
{
"filename": "src/content/watchers/helpers/postList.ts",
"retrieved_chunk": " }\n #onTabButtonClick(event: MouseEvent): void {\n const target = event.target as HTMLElement;\n const data = target.getAttribute('data-testid');\n if (data === FOLLOWING_DATA || target.querySelector(`[data-testid=\"${FOLLOWING_DATA}\"]`)) {\n if (this.#activeTabSelector !== FOLLOWING_FEED) this.#currentPost = null;\n this.#activeTabSelector = FOLLOWING_FEED;\n } else if (data === WHATSHOT_DATA || target.querySelector(`[data-testid=\"${WHATSHOT_DATA}\"]`)) {\n if (this.#activeTabSelector !== WHATSHOT_FEED) this.#currentPost = null;\n this.#activeTabSelector = WHATSHOT_FEED;",
"score": 39.38556501069934
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " if (target?.tagName.toLowerCase() === 'button') return;\n if (!this.#modal?.contains(event.target as Node) && event.target !== this.#exitButton) {\n this.#eventKeeper.cancelAll();\n this.#exitButton?.click();\n }\n }\n #onPresumedSelect(): void {\n if (this.#paused) return;\n this.pause();\n document.addEventListener('mouseup', () => setTimeout(this.start.bind(this), 0), {once: true});",
"score": 34.6889307513448
},
{
"filename": "src/content/pipelines/postModal.ts",
"retrieved_chunk": " }\n start(): void {\n this.#paused = false;\n }\n pause(): void {\n this.#paused = true;\n }\n #onClick(event: MouseEvent): void {\n if (this.#paused) return;\n const target = event.target as HTMLElement;",
"score": 32.6429542508811
}
] | typescript | const agent = await getAgent(identifier, password); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.