repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
powersync-js
github_2023
powersync-ja
typescript
CrudEntry.toComparisonArray
toComparisonArray() { return [this.transactionId, this.clientId, this.op, this.table, this.id, this.opData]; }
/** * Generates an array for use in deep comparison operations */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/CrudEntry.ts#L126-L128
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SqliteBucketStorage.startSession
startSession(): void {}
/** * Reset any caches. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/SqliteBucketStorage.ts#L84-L84
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SqliteBucketStorage.deleteBucket
private async deleteBucket(bucket: string) { await this.writeTransaction(async (tx) => { await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', ['delete_bucket', bucket]); }); this.logger.debug('done deleting bucket'); this.pendingBucketDeletes = true; }
/** * Mark a bucket for deletion. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/SqliteBucketStorage.ts#L117-L124
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SqliteBucketStorage.updateObjectsFromBuckets
private async updateObjectsFromBuckets(checkpoint: Checkpoint) { return this.writeTransaction(async (tx) => { const { insertId: result } = await tx.execute('INSERT INTO powersync_operations(op, data) VALUES(?, ?)', [ 'sync_local', '' ]); return result == 1; }); }
/** * Atomically update the local state to the current checkpoint. * * This includes creating new tables, dropping old tables, and copying data over from the oplog. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/SqliteBucketStorage.ts#L179-L187
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SqliteBucketStorage.forceCompact
async forceCompact() { this.compactCounter = COMPACT_OPERATION_INTERVAL; this.pendingBucketDeletes = true; await this.autoCompact(); }
/** * Force a compact, for tests. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/SqliteBucketStorage.ts#L218-L223
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SqliteBucketStorage.getCrudBatch
async getCrudBatch(limit: number = 100): Promise<CrudBatch | null> { if (!(await this.hasCrud())) { return null; } const crudResult = await this.db.getAll<CrudEntryJSON>('SELECT * FROM ps_crud ORDER BY id ASC LIMIT ?', [limit]); const all: CrudEntry[] = []; for (const row of crudResult) { ...
/** * Get a batch of objects to send to the server. * When the objects are successfully sent to the server, call .complete() */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/SqliteBucketStorage.ts#L319-L357
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SqliteBucketStorage.setTargetCheckpoint
async setTargetCheckpoint(checkpoint: Checkpoint) { // No-op for now }
/** * Set a target checkpoint. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/bucket/SqliteBucketStorage.ts#L366-L368
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
closeReader
const closeReader = async () => { try { await reader.cancel(); } catch (ex) { // an error will throw if the reader hasn't been used yet } reader.releaseLock(); };
// This will close the network request and read stream
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/stream/AbstractRemote.ts#L452-L459
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
matchPartialObject
const matchPartialObject = (compA: object, compB: object) => { return Object.entries(compA).every(([key, value]) => { const comparisonBValue = compB[key]; if (typeof value == 'object' && typeof comparisonBValue == 'object') { return matchPartialObject(value, compa...
/** * Match only the partial status options provided in the * matching status */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/client/sync/stream/AbstractStreamingSyncImplementation.ts#L193-L201
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SyncStatus.connected
get connected() { return this.options.connected ?? false; }
/** * true if currently connected. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/db/crud/SyncStatus.ts#L20-L22
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SyncStatus.lastSyncedAt
get lastSyncedAt() { return this.options.lastSyncedAt; }
/** * Time that a last sync has fully completed, if any. * Currently this is reset to null after a restart. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/db/crud/SyncStatus.ts#L32-L34
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SyncStatus.hasSynced
get hasSynced() { return this.options.hasSynced; }
/** * Indicates whether there has been at least one full sync, if any. * Is undefined when unknown, for example when state is still being loaded from the database. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/db/crud/SyncStatus.ts#L40-L42
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SyncStatus.dataFlowStatus
get dataFlowStatus() { return ( this.options.dataFlow ?? { /** * true if actively downloading changes. * This is only true when {@link connected} is also true. */ downloading: false, /** * true if uploading changes. */ uploading: fal...
/** * Upload/download status */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/db/crud/SyncStatus.ts#L47-L61
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
Table.createTable
static createTable(name: string, table: Table) { return new Table({ name, columns: table.columns, indexes: table.indexes, localOnly: table.options.localOnly, insertOnly: table.options.insertOnly, viewName: table.options.viewName }); }
/** * Create a table. * @deprecated This was only only included for TableV2 and is no longer necessary. * Prefer to use new Table() directly. * * TODO remove in the next major release. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/db/schema/Table.ts#L68-L77
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
BaseObserver.registerListener
registerListener(listener: Partial<T>): () => void { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
/** * Register a listener for updates to the PowerSync client. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/utils/BaseObserver.ts#L21-L26
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
DataStream.enqueueData
enqueueData(data: Data) { if (this.isClosed) { throw new Error('Cannot enqueue data into closed stream.'); } this.dataQueue.push(data); this.processQueue(); }
/** * Enqueues data for the consumers to read */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/utils/DataStream.ts#L87-L95
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
DataStream.read
async read(): Promise<Data | null> { if (this.dataQueue.length <= this.lowWatermark) { await this.iterateAsyncErrored(async (l) => l.lowWater?.()); } if (this.closed) { return null; } return new Promise((resolve, reject) => { const l = this.registerListener({ data: async ...
/** * Reads data once from the data stream * @returns a Data payload or Null if the stream closed. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/utils/DataStream.ts#L101-L129
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
DataStream.forEach
forEach(callback: DataStreamCallback<Data>) { if (this.dataQueue.length <= this.lowWatermark) { this.iterateAsyncErrored(async (l) => l.lowWater?.()); } return this.registerListener({ data: callback }); }
/** * Executes a callback for each data item in the stream */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/utils/DataStream.ts#L134-L142
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
DataStream.map
map<ReturnData>(callback: (data: Data) => ReturnData): DataStream<ReturnData> { const stream = new DataStream(this.options); const l = this.registerListener({ data: async (data) => { stream.enqueueData(callback(data)); }, closed: () => { stream.close(); l?.(); } ...
/** * Creates a new data stream which is a map of the original */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/common/src/utils/DataStream.ts#L164-L177
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
getDecoder
function getDecoder(field: SQLiteColumn | SQL<unknown> | SQL.Aliased): DriverValueDecoder<unknown, unknown> { if (is(field, Column)) { return field; } else if (is(field, SQL)) { return (field as any).decoder; } else { return (field.sql as any).decoder; } }
/** * Determines the appropriate decoder for a given field. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/drizzle-driver/src/sqlite/PowerSyncSQLitePreparedQuery.ts#L142-L150
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
applyNullifyMap
function applyNullifyMap( result: Record<string, any>, nullifyMap: Record<string, string | false>, joinsNotNullableMap: Record<string, boolean> | undefined ): void { if (!joinsNotNullableMap || Object.keys(nullifyMap).length === 0) { return; } for (const [objectName, tableName] of Object.entries(nullif...
/** * Nullify all nested objects from nullifyMap that are nullable */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/drizzle-driver/src/sqlite/PowerSyncSQLitePreparedQuery.ts#L174-L188
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
PowerSyncDriver.destroy
async destroy(): Promise<void> {}
/** This will do nothing. Instead use PowerSync `disconnectAndClear` function. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/kysely-driver/src/sqlite/sqlite-driver.ts#L41-L41
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
PowerSyncDatabase.openDBAdapter
protected openDBAdapter(options: PowerSyncDatabaseOptionsWithSettings): DBAdapter { const defaultFactory = new ReactNativeQuickSqliteOpenFactory(options.database); return defaultFactory.openDB(); }
/** * Opens a DBAdapter using React Native Quick SQLite as the * default SQLite open factory. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/react-native/src/db/PowerSyncDatabase.ts#L36-L39
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
RNQSDBAdapter.readOnlyExecute
private readOnlyExecute(sql: string, params?: any[]) { return this.baseDB.readLock((ctx) => ctx.execute(sql, params)); }
/** * This provides a top-level read only execute method which is executed inside a read-lock. * This is necessary since the high level `execute` method uses a write-lock under * the hood. Helper methods such as `get`, `getAll` and `getOptional` are read only, * and should use this method. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/react-native/src/db/adapters/react-native-quick-sqlite/RNQSDBAdapter.ts#L84-L86
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
RNQSDBAdapter.generateDBHelpers
private generateDBHelpers<T extends { execute: (sql: string, params?: any[]) => Promise<QueryResult> }>( tx: T ): T & DBGetUtils { return { ...tx, /** * Execute a read-only query and return results */ getAll: async <T>(sql: string, parameters?: any[]): Promise<T[]> => { ...
/** * Adds DB get utils to lock contexts and transaction contexts * @param tx * @returns */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/react-native/src/db/adapters/react-native-quick-sqlite/RNQSDBAdapter.ts#L93-L126
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
ReactNativeStreamingSyncImplementation.initLocks
initLocks() { const { identifier } = this.options; if (identifier && LOCKS.has(identifier)) { this.locks = LOCKS.get(identifier)!; return; } this.locks = new Map<LockType, Lock>(); this.locks.set(LockType.CRUD, new Lock()); this.locks.set(LockType.SYNC, new Lock()); if (identif...
/** * Configures global locks on sync process */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/react-native/src/sync/stream/ReactNativeStreamingSyncImplementation.ts#L26-L40
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
assertValidDatabaseOptions
function assertValidDatabaseOptions(options: WebPowerSyncDatabaseOptions): void { if ('database' in options && 'encryptionKey' in options) { const { database } = options; if (isSQLOpenFactory(database) || isDBAdapter(database)) { throw new Error( `Invalid configuration: 'encryptionKey' should on...
/** * Asserts that the database options are valid for custom database constructors. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/PowerSyncDatabase.ts#L100-L109
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
PowerSyncDatabase.close
close(options: PowerSyncCloseOptions = DEFAULT_POWERSYNC_CLOSE_OPTIONS): Promise<void> { if (this.unloadListener) { window.removeEventListener('unload', this.unloadListener); } return super.close({ // Don't disconnect by default if multiple tabs are enabled disconnect: options.disconnect ...
/** * Closes the database connection. * By default the sync stream client is only disconnected if * multiple tabs are not enabled. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/PowerSyncDatabase.ts#L164-L173
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
LockedAsyncDatabaseAdapter.init
async init() { return this.initPromise; }
/** * Init is automatic, this helps catch errors or explicitly await initialization */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/LockedAsyncDatabaseAdapter.ts#L91-L93
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
LockedAsyncDatabaseAdapter.registerOnChangeListener
protected async registerOnChangeListener(db: AsyncDatabaseConnection) { this._disposeTableChangeListener = await db.registerOnTableChange((event) => { this.iterateListeners((cb) => cb.tablesUpdated?.(event)); }); }
/** * Registers a table change notification callback with the base database. * This can be extended by custom implementations in order to handle proxy events. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/LockedAsyncDatabaseAdapter.ts#L126-L130
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
LockedAsyncDatabaseAdapter.refreshSchema
async refreshSchema(): Promise<void> {}
/** * This is currently a no-op on web */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/LockedAsyncDatabaseAdapter.ts#L135-L135
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
LockedAsyncDatabaseAdapter.close
close() { this._disposeTableChangeListener?.(); this.baseDB?.close?.(); }
/** * Attempts to close the connection. * Shared workers might not actually close the connection if other * tabs are still using it. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/LockedAsyncDatabaseAdapter.ts#L150-L153
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
LockedAsyncDatabaseAdapter.wrapTransaction
private wrapTransaction<T>(cb: (tx: Transaction) => Promise<T>) { return async (tx: LockContext): Promise<T> => { await this._execute('BEGIN TRANSACTION'); let finalized = false; const commit = async (): Promise<QueryResult> => { if (finalized) { return { rowsAffected: 0 }; ...
/** * Wraps a lock context into a transaction context */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/LockedAsyncDatabaseAdapter.ts#L230-L269
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
LockedAsyncDatabaseAdapter._executeBatch
private _execute = async (sql: string, bindings?: any[]): Promise<QueryResult> => { await this.waitForInitialized(); const result = await this.baseDB.execute(sql, bindings); return { ...result, rows: { ...result.rows, item: (idx: number) => result.rows._array[idx] } }; ...
/** * Wraps the worker executeBatch function, awaiting for it to be available */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/LockedAsyncDatabaseAdapter.ts
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SSRDBAdapter.generateMockTransactionContext
private generateMockTransactionContext(): Transaction { return { ...this, commit: async () => { return MOCK_QUERY_RESPONSE; }, rollback: async () => { return MOCK_QUERY_RESPONSE; } }; }
/** * Generates a mock context for use in read/write transactions. * `this` already mocks most of the API, commit and rollback mocks * are added here */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/SSRDBAdapter.ts#L77-L87
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
WorkerWrappedAsyncDatabaseConnection.shareConnection
async shareConnection(): Promise<SharedConnectionWorker> { const { identifier, remote } = this.options; const newPort = await remote[Comlink.createEndpoint](); return { port: newPort, identifier }; }
/** * Get a MessagePort which can be used to share the internals of this connection. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts#L45-L50
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
WorkerWrappedAsyncDatabaseConnection.registerOnTableChange
async registerOnTableChange(callback: OnTableChangeCallback) { return this.baseConnection.registerOnTableChange(Comlink.proxy(callback)); }
/** * Registers a table change notification callback with the base database. * This can be extended by custom implementations in order to handle proxy events. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts#L56-L58
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
WASqliteConnection.executeBatch
async executeBatch(sql: string, bindings?: any[][]): Promise<ProxiedQueryResult> { return this.acquireExecuteLock(async (): Promise<ProxiedQueryResult> => { let affectedRows = 0; try { await this.executeSingleStatement('BEGIN TRANSACTION'); const wrappedBindings = bindings ? bindings :...
/** * This executes SQL statements in a batch. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/wa-sqlite/WASQLiteConnection.ts#L271-L325
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
WASqliteConnection.execute
async execute(sql: string | TemplateStringsArray, bindings?: any[]): Promise<ProxiedQueryResult> { // Running multiple statements on the same connection concurrently should not be allowed return this.acquireExecuteLock(async () => { return this.executeSingleStatement(sql, bindings); }); }
/** * This executes single SQL statements inside a requested lock. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/wa-sqlite/WASQLiteConnection.ts#L330-L335
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
WASqliteConnection.acquireExecuteLock
protected acquireExecuteLock = <T>(callback: () => Promise<T>): Promise<T> => { return this.statementMutex.runExclusive(callback); }
/** * This requests a lock for executing statements. * Should only be used internally. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/wa-sqlite/WASQLiteConnection.ts
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
WASqliteConnection.executeSingleStatement
protected async executeSingleStatement( sql: string | TemplateStringsArray, bindings?: any[] ): Promise<ProxiedQueryResult> { const results = []; for await (const stmt of this.sqliteAPI.statements(this.dbP, sql as string)) { let columns; const wrappedBindings = bindings ? [bindings] : [[]]...
/** * This executes a single statement using SQLite3. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/wa-sqlite/WASQLiteConnection.ts#L359-L419
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
assertValidWASQLiteOpenFactoryOptions
function assertValidWASQLiteOpenFactoryOptions(options: WASQLiteOpenFactoryOptions): void { // The OPFS VFS only works in dedicated web workers. if ('vfs' in options && 'flags' in options) { const { vfs, flags = {} } = options; if (vfs !== WASQLiteVFS.IDBBatchAtomicVFS && 'useWebWorker' in flags && !flags.u...
/** * Asserts that the factory options are valid. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts#L116-L126
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SSRStreamingSyncImplementation.connect
async connect(options?: PowerSyncConnectionOptions): Promise<void> {}
/** * This is a no-op in SSR mode */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SSRWebStreamingSyncImplementation.ts#L37-L37
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SSRStreamingSyncImplementation.disconnect
async disconnect(): Promise<void> {}
/** * This is a no-op in SSR mode */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SSRWebStreamingSyncImplementation.ts#L44-L44
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SSRStreamingSyncImplementation.waitForReady
async waitForReady() {}
/** * This SSR Mode implementation is immediately ready. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SSRWebStreamingSyncImplementation.ts#L49-L49
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SSRStreamingSyncImplementation.waitForStatus
async waitForStatus(status: SyncStatusOptions) { return new Promise<void>((r) => {}); }
/** * This will never resolve in SSR Mode. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SSRWebStreamingSyncImplementation.ts#L54-L56
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SSRStreamingSyncImplementation.getWriteCheckpoint
async getWriteCheckpoint() { return '1'; }
/** * Returns a placeholder checkpoint. This should not be used. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SSRWebStreamingSyncImplementation.ts#L61-L63
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SSRStreamingSyncImplementation.hasCompletedSync
async hasCompletedSync() { return false; }
/** * The SSR mode adapter will never complete syncing. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SSRWebStreamingSyncImplementation.ts#L68-L70
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SSRStreamingSyncImplementation.triggerCrudUpload
triggerCrudUpload() {}
/** * This is a no-op in SSR mode. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SSRWebStreamingSyncImplementation.ts#L75-L75
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SharedWebStreamingSyncImplementation.connect
async connect(options?: PowerSyncConnectionOptions): Promise<void> { await this.waitForReady(); // This is needed since a new tab won't have any reference to the // shared worker sync implementation since that is only created on the first call to `connect`. await this.disconnect(); return this.syncM...
/** * Starts the sync process, this effectively acts as a call to * `connect` if not yet connected. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SharedWebStreamingSyncImplementation.ts#L182-L188
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SharedWebStreamingSyncImplementation._testUpdateStatus
private async _testUpdateStatus(status: SyncStatus) { await this.isInitialized; return (this.syncManager as any)['_testUpdateAllStatuses'](status.toJSON()); }
/** * Used in tests to force a connection states */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/db/sync/SharedWebStreamingSyncImplementation.ts#L225-L228
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
BroadcastLogger.iterateClients
protected async iterateClients(callback: (client: WrappedSyncPort) => Promise<void>) { for (const client of this.clients) { try { await callback(client); } catch (ex) { console.error('Caught exception when iterating client', ex); } } }
/** * Iterates all clients, catches individual client exceptions * and proceeds to execute for all clients. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/worker/sync/BroadcastLogger.ts#L90-L98
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
BroadcastLogger.sanitizeArgs
protected sanitizeArgs(x: any[]): any[] { const sanitizedParams = x.map((param) => { try { // Try and clone here first. If it fails it won't be passable over a MessagePort return structuredClone(param); } catch (ex) { console.error(ex); return 'Could not serialize log par...
/** * Guards against any logging errors. * We don't want a logging exception to cause further issues upstream */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/worker/sync/BroadcastLogger.ts#L104-L116
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SharedSyncImplementation.setParams
async setParams(params: SharedSyncInitOptions) { if (this.syncParams) { // Cannot modify already existing sync implementation return; } this.syncParams = params; if (params.streamOptions?.flags?.broadcastLogs) { this.logger = this.broadCastLogger; } self.onerror = (event) =>...
/** * Configures the DBAdapter connection and a streaming sync client. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/worker/sync/SharedSyncImplementation.ts#L146-L165
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SharedSyncImplementation.connect
async connect(options?: PowerSyncConnectionOptions) { await this.waitForReady(); // This effectively queues connect and disconnect calls. Ensuring multiple tabs' requests are synchronized return getNavigatorLocks().request('shared-sync-connect', async () => { this.syncStreamClient = this.generateStrea...
/** * Connects to the PowerSync backend instance. * Multiple tabs can safely call this in their initialization. * The connection will simply be reconnected whenever a new tab * connects. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/worker/sync/SharedSyncImplementation.ts#L179-L193
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SharedSyncImplementation.addPort
addPort(port: MessagePort) { const portProvider = { port, clientProvider: Comlink.wrap<AbstractSharedSyncClientProvider>(port) }; this.ports.push(portProvider); // Give the newly connected client the latest status const status = this.syncStreamClient?.syncStatus; if (status) { ...
/** * Adds a new client tab's message port to the list of connected ports */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/worker/sync/SharedSyncImplementation.ts#L208-L220
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SharedSyncImplementation.removePort
async removePort(port: MessagePort) { const index = this.ports.findIndex((p) => p.port == port); if (index < 0) { console.warn(`Could not remove port ${port} since it is not present in active ports.`); return; } const trackedPort = this.ports[index]; if (trackedPort.db) { trackedP...
/** * Removes a message port client from this manager's managed * clients. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/worker/sync/SharedSyncImplementation.ts#L226-L258
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SharedSyncImplementation.updateAllStatuses
private updateAllStatuses(status: SyncStatusOptions) { this.syncStatus = new SyncStatus(status); this.ports.forEach((p) => p.clientProvider.statusChanged(status)); }
/** * A method to update the all shared statuses for each * client. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/worker/sync/SharedSyncImplementation.ts#L360-L363
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
SharedSyncImplementation._testUpdateAllStatuses
private _testUpdateAllStatuses(status: SyncStatusOptions) { if (!this.syncStreamClient) { // This is just for testing purposes this.syncStreamClient = this.generateStreamingImplementation(); } // Only assigning, don't call listeners for this test this.syncStreamClient!.syncStatus = new Sync...
/** * A function only used for unit tests which updates the internal * sync stream client and all tab client's sync status */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/src/worker/sync/SharedSyncImplementation.ts#L369-L379
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
itWithDBs
const itWithDBs = (name: string, test: (db: AbstractPowerSyncDatabase) => Promise<void>) => { it(`${name} - with web worker`, () => test(dbWithWebWorker)); it(`${name} - without web worker`, () => test(dbWithoutWebWorker)); };
/** * Declares a test to be executed with multiple DB connections */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/tests/main.test.ts#L19-L22
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
generateAssetsTable
const generateAssetsTable = (weightColumnName: string = 'weight', includeIndexes = true, indexAscending = true) => new Table({ name: 'assets', columns: [ new Column({ name: 'created_at', type: ColumnType.TEXT }), new Column({ name: 'make', type: ColumnType.TEXT }), new Column({ name: 'model'...
/** * Generates the Asset table with configurable options which * will be modified later. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/tests/schema.test.ts#L13-L39
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
generateSchemaTables
const generateSchemaTables = (assetsTableGenerator: () => Table = generateAssetsTable) => [ assetsTableGenerator(), new Table({ name: 'customers', columns: [new Column({ name: 'name', type: ColumnType.TEXT }), new Column({ name: 'email', type: ColumnType.TEXT })] }), new Table({ name: 'logs', in...
/** * Generates all the schema tables. * Allows for a custom assets table generator to be supplied. */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/tests/schema.test.ts#L45-L70
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
itWithGenerators
const itWithGenerators = async ( name: string, test: (createConnectedDatabase: () => ReturnType<typeof generateConnectedDatabase>) => Promise<void> ) => { const funcWithWebWorker = generateConnectedDatabase; const funcWithoutWebWorker = () => generateConnectedDatabase({ powerSyncOptions:...
/** * Declares a test to be executed with different generated db functions */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/tests/stream.test.ts#L98-L114
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
TestPowerSyncDatabase.testResolvedConnectionOptions
public testResolvedConnectionOptions(options?: any) { return this.resolvedConnectionOptions(options); }
// Expose protected method for testing
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/packages/web/tests/src/db/AbstractPowerSyncDatabase.test.ts#L29-L31
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
ensureTmpDirExists
const ensureTmpDirExists = async () => { try { await fs.mkdir(tmpDir, { recursive: true }); } catch (err) { console.error(`Error creating tmp directory: ${err}`); } };
// Ensure tmp directory exists
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/scripts/isolated-demo-test.ts#L48-L54
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
updateDependencies
const updateDependencies = async (packageJsonPath: string) => { const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf8')); const updateDeps = async (deps: { [key: string]: string }) => { for (const dep in deps) { if (deps[dep].startsWith('workspace:')) { const matchingPackage = w...
// Function to update dependencies in package.json
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/scripts/isolated-demo-test.ts#L59-L80
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
processDemo
const processDemo = async (demoName: string): Promise<DemoResult> => { const demoSrc = path.join(demosDir, demoName); const demoDest = path.join(tmpDir, demoName); console.log(`Processing ${demoName}`); console.log(`Demo will be copied to: ${demoDest}`); // Copy demo to tmp directory (without node modules)...
// Function to process each demo
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/scripts/isolated-demo-test.ts#L83-L134
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
main
const main = async () => { const results: DemoResult[] = []; try { await ensureTmpDirExists(); const demoNames = await fs.readdir(demosDir); for (const demoName of demoNames) { try { results.push(await processDemo(demoName)); } catch (ex) { results.push({ name: de...
// Main function to read demos directory and process each demo
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/scripts/isolated-demo-test.ts#L137-L188
e1904547f3641eb8fa505dbf0cbd21fae6233a49
powersync-js
github_2023
powersync-ja
typescript
processPackageJson
const processPackageJson = (packageJsonPath: string) => { // Read and parse package.json const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')); // Remove the publishConfig.registry if it exists if (packageJson.publishConfig && packageJson.publishConfig.registry) { delete packageJson.pub...
/** * Deletes publishConfig.registry if present */
https://github.com/powersync-ja/powersync-js/blob/e1904547f3641eb8fa505dbf0cbd21fae6233a49/scripts/test-publish-helper.ts#L16-L27
e1904547f3641eb8fa505dbf0cbd21fae6233a49
Joi
github_2023
watchingfun
typescript
bindingSqlite3
function bindingSqlite3( options: { output?: string; better_sqlite3_node?: string; command?: string; } = {} ): Plugin { const TAG = "[vite-plugin-binding-sqlite3]"; options.output ??= "dist-native"; options.better_sqlite3_node ??= "better_sqlite3.node"; options.command ??= "build"; return { name: "vite-...
// https://github.com/WiseLibs/better-sqlite3/blob/v8.5.2/lib/database.js#L36
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/vite.config.ts#L82-L125
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
withPrototype
function withPrototype(obj: Record<string, any>) { const protos = Object.getPrototypeOf(obj); for (const [key, value] of Object.entries(protos)) { if (Object.prototype.hasOwnProperty.call(obj, key)) continue; if (typeof value === "function") { // Some native APIs, like `NodeJS.EventEmitter['on']`, don't work...
// `exposeInMainWorld` can't detect attributes and methods of `prototype`, manually patching it.
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/electron/preload.ts#L8-L24
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
domReady
function domReady(condition: DocumentReadyState[] = ["complete", "interactive"]) { return new Promise((resolve) => { if (condition.includes(document.readyState)) { resolve(true); } else { document.addEventListener("readystatechange", () => { if (condition.includes(document.readyState)) { resolve(tru...
// --------- Preload scripts loading ---------
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/electron/preload.ts#L27-L39
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
useLoading
function useLoading() { const className = `loaders-css__square-spin`; const oStyle = document.createElement("style"); const oDiv = document.createElement("div"); //防止闪烁 const oStyle2 = document.createElement("style"); oStyle2.innerHTML = ".loading-container{opacity:0;}"; oStyle.id = "app-loading-style"; oStyle...
/** * https://tobiasahlin.com/spinkit * https://codepen.io/tylertonyjohnson/full/XWxqLrj */
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/electron/preload.ts#L58-L85
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
wsSubscribe
function wsSubscribe(ws: LeagueWebSocket) { ws.subscribe("/lol-gameflow/v1/gameflow-phase", async (data) => { logger.info("gameflow-phase", data); sendToWebContent(Handle.gameFlowPhase, data); Object.values(LCUEventHandlers).forEach((handler) => handler(data)); }); }
//ws连接并监听事件
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/electron/lcu/connector.ts#L97-L103
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
getOpggRankData
async function getOpggRankData() { // if (!opggRankData) { // let response = await fetch(OPGG_DATA_URL); // await checkResponse(response); // opggRankData = (await response.json()) as ChampionsPopularData; // } // return opggRankData; return opggRankDataJson as ChampionsPopularData; }
//let opggRankData: ChampionsPopularData | null;
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/electron/lcu/opgg.ts#L28-L36
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
combineMessageAndSplat
const combineMessageAndSplat = () => ({ transform(info: TransformableInfo) { const { [Symbol.for("splat")]: args = [], message } = info; info.message = util.format(message, ...args); return info; } });
// https://github.com/winstonjs/winston/issues/1427
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/electron/lib/logger.ts#L11-L17
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
updateTeamsInfo
async function updateTeamsInfo(teams: TeamMember[][]) { const currentSummoner = await getCurrentSummoner(); const myTeamMemberIndex = teams.findIndex((arr) => arr.find((t) => t.puuid === currentSummoner.puuid)); updateMyTeamInfo(teams[myTeamMemberIndex]); await updateTheirTeamInfo(teams[myTeamMemberIndex === 0 ...
//更新队伍信息
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/src/store/lcu.ts#L162-L201
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
updateMyTeamInfo
function updateMyTeamInfo(teamMembers: TeamMember[]) { myTeam.value = teamMembers.map((t) => { const originInfo = myTeam.value.find((i) => i.puuid === t.puuid); return { ...originInfo, assignedPosition: t.selectedPosition?.toLowerCase(), championId: t.championId } as TeamMemberInfo; }); }
//刚进入房间时就只能得到召唤师信息,进入游戏前得到位置英雄等信息然后更新下
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/src/store/lcu.ts#L216-L225
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
toNum
function toNum(a: string) { const c = a.toString().split("."); const num_place = ["", "0", "00", "000", "0000"], r = num_place.reverse(); for (let i = 0; i < c.length; i++) { const len = c[i].length; c[i] = r[len] + c[i]; } return c.join(""); }
//计算版本号大小,转化大小
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/src/utils/updateCheck.ts#L37-L46
6986349877937e00dff155074478f947679ee096
Joi
github_2023
watchingfun
typescript
checkPlugin
function checkPlugin(a: string, b: string) { const numA = toNum(a); const numB = toNum(b); return numA > numB ? 1 : numA < numB ? -1 : 0; }
//检测版本号是否需要更新
https://github.com/watchingfun/Joi/blob/6986349877937e00dff155074478f947679ee096/src/utils/updateCheck.ts#L49-L53
6986349877937e00dff155074478f947679ee096
wyw-in-js
github_2023
Anber
typescript
CssProcessor.addInterpolation
public override addInterpolation( node: unknown, precedingCss: string, source: string ): string { throw new Error( `css tag cannot handle '${source}' as an interpolated value` ); }
// eslint-disable-next-line class-methods-use-this
https://github.com/Anber/wyw-in-js/blob/05d3d7234728a8574792d185a8fcb412696707fa/examples/template-tag-syntax/src/processors/css.ts#L16-L24
05d3d7234728a8574792d185a8fcb412696707fa
wyw-in-js
github_2023
Anber
typescript
throwIfInvalid
function throwIfInvalid<T>( checker: (value: unknown) => value is T, value: Error | unknown, ex: { buildCodeFrameError: BuildCodeFrameErrorFn }, source: string ): asserts value is T { // We can't use instanceof here so let's use duck typing if (isLikeError(value) && value.stack && value.message) { throw...
// Throw if we can't handle the interpolated value
https://github.com/Anber/wyw-in-js/blob/05d3d7234728a8574792d185a8fcb412696707fa/packages/processor-utils/src/utils/throwIfInvalid.ts#L10-L46
05d3d7234728a8574792d185a8fcb412696707fa
wyw-in-js
github_2023
Anber
typescript
UInt32
function UInt32(str: string, pos: number) { return ( str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8) + (str.charCodeAt(pos++) << 16) + (str.charCodeAt(pos) << 24) ); }
/* eslint-disable no-plusplus, no-bitwise, default-case, no-param-reassign, prefer-destructuring */
https://github.com/Anber/wyw-in-js/blob/05d3d7234728a8574792d185a8fcb412696707fa/packages/shared/src/slugify.ts#L10-L17
05d3d7234728a8574792d185a8fcb412696707fa
wyw-in-js
github_2023
Anber
typescript
Entrypoint.create
protected static create( services: Services, parent: ParentEntrypoint | null, name: string, only: string[], loadedCode: string | undefined ): Entrypoint | 'loop' { const { cache, eventEmitter } = services; return eventEmitter.perf('createEntrypoint', () => { const [status, entrypoint...
/** * Creates an entrypoint for the specified file. * If there is already an entrypoint for this file, there will be four possible outcomes: * 1. If `loadedCode` is specified and is different from the one that was used to create the existing entrypoint, * the existing entrypoint will be superseded by a ne...
https://github.com/Anber/wyw-in-js/blob/05d3d7234728a8574792d185a8fcb412696707fa/packages/transform/src/transform/Entrypoint.ts#L140-L171
05d3d7234728a8574792d185a8fcb412696707fa
wyw-in-js
github_2023
Anber
typescript
isType
const isType = (p: { node: { importKind?: 'type' | unknown } | { exportKind?: 'type' | unknown }; }): boolean => ('importKind' in p.node && p.node.importKind === 'type') || ('exportKind' in p.node && p.node.exportKind === 'type');
// We ignore imports and exports of types
https://github.com/Anber/wyw-in-js/blob/05d3d7234728a8574792d185a8fcb412696707fa/packages/transform/src/utils/collectExportsAndImports.ts#L89-L93
05d3d7234728a8574792d185a8fcb412696707fa
wyw-in-js
github_2023
Anber
typescript
isInDelete
function isInDelete(path: { parentPath: NodePath<UnaryExpression> }): boolean { return path.parentPath.node.operator === 'delete'; }
// It's possible for non-strict mode code to have variable deletions.
https://github.com/Anber/wyw-in-js/blob/05d3d7234728a8574792d185a8fcb412696707fa/packages/transform/src/utils/findIdentifiers.ts#L20-L22
05d3d7234728a8574792d185a8fcb412696707fa
wyw-in-js
github_2023
Anber
typescript
referenceEnums
function referenceEnums(program: NodePath<Program>) { /* * We are looking for transpiled enums. * (function (Colors) { * Colors["BLUE"] = "#27509A"; * })(Colors || (Colors = {})); */ program.traverse({ ExpressionStatement(expressionStatement) { const expression = expressionStatement...
// @babel/preset-typescript transpiles enums, but doesn't reference used identifiers.
https://github.com/Anber/wyw-in-js/blob/05d3d7234728a8574792d185a8fcb412696707fa/packages/transform/src/utils/scopeHelpers.ts#L470-L491
05d3d7234728a8574792d185a8fcb412696707fa
wyw-in-js
github_2023
Anber
typescript
setReferencePropertyIfNotPresent
function setReferencePropertyIfNotPresent( context: vm.Context, key: string ): void { if (context[key] === context) { return; } context[key] = context; }
/** * `happy-dom` already has required references, so we don't need to set them. */
https://github.com/Anber/wyw-in-js/blob/05d3d7234728a8574792d185a8fcb412696707fa/packages/transform/src/vm/createVmContext.ts#L27-L36
05d3d7234728a8574792d185a8fcb412696707fa
lunaria
github_2023
lunariajs
typescript
main
async function main() { try { const { name, options } = parseCommand(); if (name && options.help) { await showHelp(name); return; } switch (name) { case 'build': const { build } = await import('./build/index.js'); await build(options); break; case 'init': const { init } = await im...
/** CLI entrypoint */
https://github.com/lunariajs/lunaria/blob/558e9ec18e7f9aeaf45e6337b415510e5612ab43/packages/core/src/cli/index.ts#L73-L112
558e9ec18e7f9aeaf45e6337b415510e5612ab43
lunaria
github_2023
lunariajs
typescript
stringify
const stringify = (val: unknown) => JSON.stringify(val, null, 1).split(newlinePlusWhitespace).join(' ');
/** `JSON.stringify()` a value with spaces around object/array entries. */
https://github.com/lunariajs/lunaria/blob/558e9ec18e7f9aeaf45e6337b415510e5612ab43/packages/core/src/config/error-map.ts#L122-L123
558e9ec18e7f9aeaf45e6337b415510e5612ab43
obsidian-multi-properties
github_2023
technohiker
typescript
PropModal.onConfirm
onConfirm(bool: boolean) { if (bool) { this.submission(this.props); this.close(); } }
//Run form submission if user clicks confirm.
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/AddPropModal.ts#L34-L39
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
PropModal.onSubmit
onSubmit(props: Map<string, NewPropData>) { this.props = props; new AddConfirmModal( this.app, this.props, this.overwrite, this.onConfirm.bind(this) ).open(); }
//Pull up confirmation form when user submits base form.
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/AddPropModal.ts#L47-L55
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
canBeAppended
function canBeAppended(str1: string, str2: string) { let arr = ["number", "date", "datetime", "checkbox"]; //These values should not be appended. if (arr.includes(str1) || arr.includes(str2)) return false; return true; }
/** Check if two types can be appended to each other. */
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/frontmatter.ts#L62-L66
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
mergeIntoArrays
function mergeIntoArrays(...args: (string | string[])[]): string[] { const arrays = args.map((arg) => (Array.isArray(arg) ? arg : [arg])); // Flatten the array const flattened = arrays.flat(); // Remove duplicates using Set and spread it into an array const unique = [...new Set(flattened)]; return unique...
/** Convert strings and arrays into single array. */
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/frontmatter.ts#L69-L79
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
MultiPropPlugin.searchFolders
searchFolders(folder: TFolder, callback: (file: TFile) => any) { for (let obj of folder.children) { if (obj instanceof TFolder) { if (this.settings.recursive) { this.searchFolders(obj, callback); } } if (obj instanceof TFile && obj.extension === "md") { callback(o...
/** Iterates through all files in a folder and runs callback on each file. */
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/main.ts#L156-L167
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
MultiPropPlugin.searchFiles
searchFiles(files: TAbstractFile[], callback: (file: TFile) => any) { for (let file of files) { if (file instanceof TFile && file.extension === "md") { callback(file); } } }
/** Iterates through selection of files and runs a given callback function on that file. */
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/main.ts#L170-L176
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
MultiPropPlugin.getFilesFromSearch
getFilesFromSearch(leaf: any) { let files: TFile[] = []; leaf.dom.vChildren.children.forEach((e: any) => { files.push(e.file); }); return files; }
/** Get all files from a search result. */
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/main.ts#L179-L185
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
MultiPropPlugin.createPropModal
createPropModal(iterable: TAbstractFile[] | TFolder) { let iterateFunc; this.app.vault.getAllLoadedFiles; if (iterable instanceof TFolder) { iterateFunc = (props: Map<string, any>) => this.searchFolders(iterable, this.addPropsCallback(props)); } else { iterateFunc = (props: Map<strin...
/** Create modal for adding properties. * Will call a different function depending on whether files or a folder is used. */
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/main.ts#L189-L228
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
MultiPropPlugin.createRemoveModal
async createRemoveModal(iterable: TAbstractFile[] | TFolder) { let names; let iterateFunc; if (iterable instanceof TFolder) { names = await this.getPropsFromFolder(iterable, new Set()); iterateFunc = (props: string[]) => this.searchFolders(iterable, this.removePropsCallback(props)); ...
/** Create modal for removing properties. * Will call a different function depending on whether files or a folder is used. */
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/main.ts#L232-L255
c7c41a571d7e85946694a97e45ba8c8b977c1413
obsidian-multi-properties
github_2023
technohiker
typescript
MultiPropPlugin.readYamlProperties
readYamlProperties(file: TFile) { const metadata = this.app.metadataCache.getFileCache(file); const frontmatter = metadata?.frontmatter; console.log({ frontmatter }); if (!frontmatter) { new Notice("Not a valid Props template.", 4000); return; } const allPropsWithType = this.app.m...
/** Read through a given file and get name/value of props. * Revised from https://forum.obsidian.md/t/how-to-programmatically-access-a-files-properties-types/77826/4. */
https://github.com/technohiker/obsidian-multi-properties/blob/c7c41a571d7e85946694a97e45ba8c8b977c1413/src/main.ts#L260-L286
c7c41a571d7e85946694a97e45ba8c8b977c1413