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) { all.push(CrudEntry.fromRow(row)); } if (all.length === 0) { return null; } const last = all[all.length - 1]; return { crud: all, haveMore: true, complete: async (writeCheckpoint?: string) => { return this.writeTransaction(async (tx) => { await tx.execute('DELETE FROM ps_crud WHERE id <= ?', [last.clientId]); if (writeCheckpoint) { const crudResult = await tx.execute('SELECT 1 FROM ps_crud LIMIT 1'); if (crudResult.rows?.length) { await tx.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'", [ writeCheckpoint ]); } } else { await tx.execute("UPDATE ps_buckets SET target_op = CAST(? as INTEGER) WHERE name='$local'", [ this.getMaxOpId() ]); } }); } }; }
/** * 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, comparisonBValue); } return value == comparisonBValue; }); };
/** * 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: false } ); }
/** * 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 (data) => { resolve(data); // Remove the listener l?.(); }, closed: () => { resolve(null); l?.(); }, error: (ex) => { reject(ex); l?.(); } }); this.processQueue(); }); }
/** * 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?.(); } }); return stream; }
/** * 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(nullifyMap)) { if (typeof tableName === 'string' && !joinsNotNullableMap[tableName]) { result[objectName] = null; } } }
/** * 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[]> => { const res = await tx.execute(sql, parameters); return res.rows?._array ?? []; }, /** * Execute a read-only query and return the first result, or null if the ResultSet is empty. */ getOptional: async <T>(sql: string, parameters?: any[]): Promise<T | null> => { const res = await tx.execute(sql, parameters); return res.rows?.item(0) ?? null; }, /** * Execute a read-only query and return the first result, error if the ResultSet is empty. */ get: async <T>(sql: string, parameters?: any[]): Promise<T> => { const res = await tx.execute(sql, parameters); const first = res.rows?.item(0); if (!first) { throw new Error('Result set is empty'); } return first; } }; }
/** * 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 (identifier) { LOCKS.set(identifier, this.locks); } }
/** * 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 only be included inside the database object when using a custom ${isSQLOpenFactory(database) ? 'WASQLiteOpenFactory' : 'WASQLiteDBAdapter'} constructor.` ); } } }
/** * 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 ?? !this.resolvedFlags.enableMultiTabs }); }
/** * 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 }; } finalized = true; return this._execute('COMMIT'); }; const rollback = () => { finalized = true; return this._execute('ROLLBACK'); }; try { const result = await cb({ ...tx, commit, rollback }); if (!finalized) { await commit(); } return result; } catch (ex) { this.logger.debug('Caught ex in transaction', ex); try { await rollback(); } catch (ex2) { // In rare cases, a rollback may fail. // Safe to ignore. } throw ex; } }; }
/** * 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 : []; for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) { if (stmt === null) { return { rowsAffected: 0, rows: { _array: [], length: 0 } }; } //Prepare statement once for (const binding of wrappedBindings) { // TODO not sure why this is needed currently, but booleans break for (let i = 0; i < binding.length; i++) { const b = binding[i]; if (typeof b == 'boolean') { binding[i] = b ? 1 : 0; } } if (bindings) { this.sqliteAPI.bind_collection(stmt, binding); } const result = await this.sqliteAPI.step(stmt); if (result === SQLite.SQLITE_DONE) { //The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero. affectedRows += this.sqliteAPI.changes(this.dbP); } this.sqliteAPI.reset(stmt); } } await this.executeSingleStatement('COMMIT'); } catch (err) { await this.executeSingleStatement('ROLLBACK'); return { rowsAffected: 0, rows: { _array: [], length: 0 } }; } const result = { rowsAffected: affectedRows, rows: { _array: [], length: 0 } }; return result; }); }
/** * 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] : [[]]; for (const binding of wrappedBindings) { // TODO not sure why this is needed currently, but booleans break binding.forEach((b, index, arr) => { if (typeof b == 'boolean') { arr[index] = b ? 1 : 0; } }); this.sqliteAPI.reset(stmt); if (bindings) { this.sqliteAPI.bind_collection(stmt, binding); } const rows = []; while ((await this.sqliteAPI.step(stmt)) === SQLite.SQLITE_ROW) { const row = this.sqliteAPI.row(stmt); rows.push(row); } columns = columns ?? this.sqliteAPI.column_names(stmt); if (columns.length) { results.push({ columns, rows }); } } // When binding parameters, only a single statement is executed. if (bindings) { break; } } const rows: Record<string, any>[] = []; for (const resultSet of results) { for (const row of resultSet.rows) { const outRow: Record<string, any> = {}; resultSet.columns.forEach((key, index) => { outRow[key] = row[index]; }); rows.push(outRow); } } const result = { insertId: this.sqliteAPI.last_insert_id(this.dbP), rowsAffected: this.sqliteAPI.changes(this.dbP), rows: { _array: rows, length: rows.length } }; return result; }
/** * 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.useWebWorker) { throw new Error( `Invalid configuration: The 'useWebWorker' flag must be true when using an OPFS-based VFS (${vfs}).` ); } } }
/** * 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.syncManager.connect(options); }
/** * 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 params. Check shared worker logs for more details.'; } }); return sanitizedParams; }
/** * 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) => { // Share any uncaught events on the broadcast logger this.logger.error('Uncaught exception in PowerSync shared sync worker', event); }; await this.openInternalDB(); this.iterateListeners((l) => l.initialized?.()); }
/** * 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.generateStreamingImplementation(); this.lastConnectOptions = options; this.syncStreamClient.registerListener({ statusChanged: (status) => { this.updateAllStatuses(status.toJSON()); } }); await this.syncStreamClient.connect(options); }); }
/** * 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) { portProvider.clientProvider.statusChanged(status.toJSON()); } }
/** * 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) { trackedPort.db.close(); } // Release proxy trackedPort.clientProvider[Comlink.releaseProxy](); this.ports.splice(index, 1); /** * The port might currently be in use. Any active functions might * not resolve. Abort them here. */ [this.fetchCredentialsController, this.uploadDataController].forEach((abortController) => { if (abortController?.activePort.port == port) { abortController!.controller.abort(new AbortOperation('Closing pending requests after client port is removed')); } }); if (this.dbAdapter == trackedPort.db && this.syncStreamClient) { await this.disconnect(); // Ask for a new DB worker port handler await this.openInternalDB(); await this.connect(this.lastConnectOptions); } }
/** * 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 SyncStatus(status); this.updateAllStatuses(status); }
/** * 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', type: ColumnType.TEXT }), new Column({ name: 'serial_number', type: ColumnType.TEXT }), new Column({ name: 'quantity', type: ColumnType.INTEGER }), new Column({ name: 'user_id', type: ColumnType.TEXT }), new Column({ name: weightColumnName, type: ColumnType.REAL }), new Column({ name: 'description', type: ColumnType.TEXT }) ], indexes: includeIndexes ? [ new Index({ name: 'makemodel', columns: [ new IndexedColumn({ name: 'make' }), new IndexedColumn({ name: 'model', ascending: indexAscending }) ] }) ] : [] });
/** * 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', insertOnly: true, columns: [ new Column({ name: 'level', type: ColumnType.TEXT }), new Column({ name: 'content', type: ColumnType.TEXT }) ] }), new Table({ name: 'credentials', localOnly: true, columns: [new Column({ name: 'key', type: ColumnType.TEXT }), new Column({ name: 'value', type: ColumnType.TEXT })] }), new Table({ name: 'aliased', columns: [new Column({ name: 'name', type: ColumnType.TEXT })], viewName: 'test1' }) ];
/** * 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: { flags: { useWebWorker: false } } }); it(`${name} - with web worker`, () => test(funcWithWebWorker)); it(`${name} - without web worker`, () => test(funcWithoutWebWorker)); };
/** * 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 = workspacePackages.find((p) => p.manifest.name == dep); deps[dep] = `^${matchingPackage!.manifest.version!}`; } } }; if (packageJson.dependencies) { await updateDeps(packageJson.dependencies); } if (packageJson.devDependencies) { await updateDeps(packageJson.devDependencies); } await fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8'); };
// 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) await fs.cp(demoSrc, demoDest, { recursive: true, filter: (source) => !source.includes('node_modules') }); // Update package.json const packageJsonPath = path.join(demoDest, 'package.json'); await updateDependencies(packageJsonPath); const result: DemoResult = { name: demoName, installResult: { state: TestState.WARN }, buildResult: { state: TestState.WARN } }; // Run pnpm install and pnpm build try { execSync('pnpm install', { cwd: demoDest, stdio: 'inherit' }); result.installResult.state = TestState.PASSED; } catch (ex) { result.installResult.state = TestState.FAILED; result.installResult.error = ex.message; return result; } const packageJSONPath = path.join(demoDest, 'package.json'); const pkg = JSON.parse(await fs.readFile(packageJSONPath, 'utf-8')); if (!pkg.scripts['test:build']) { result.buildResult.state = TestState.WARN; return result; } try { execSync('pnpm run test:build', { cwd: demoDest, stdio: 'inherit' }); result.buildResult.state = TestState.PASSED; } catch (ex) { result.buildResult.state = TestState.FAILED; result.buildResult.error = ex.message; } return result; };
// 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: demoName, installResult: { state: TestState.FAILED, error: ex.message }, buildResult: { state: TestState.FAILED } }); console.log(`::error file=${demoName},line=1,col=1::${ex}`); } } } catch (err) { console.error(`Error processing demos: ${err}`); process.exit(1); } const errored = !!results.find( (r) => r.installResult.state == TestState.FAILED || r.buildResult.state == TestState.FAILED ); await core.summary .addHeading('Test Results') .addTable([ [ { data: 'Demo', header: true }, { data: 'Install', header: true }, { data: 'Build', header: true } ], ...results.map((r) => [r.name, displayState(r.installResult.state), displayState(r.buildResult.state)]) ]) .write(); if (errored) { console.error(`Some demos did not pass`); process.exit(1); } else { console.log('All demos processed successfully.'); } };
// 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.publishConfig.registry; } // Write the modified package.json back to the file system fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2)); };
/** * 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-plugin-binding-sqlite3", config(config) { // https://github.com/vitejs/vite/blob/v4.4.9/packages/vite/src/node/config.ts#L496-L499 const resolvedRoot = normalizePath(config.root ? path.resolve(config.root) : process.cwd()); const output = path.resolve(resolvedRoot, options.output as string); const better_sqlite3 = require.resolve("better-sqlite3"); const better_sqlite3_root = path.join( better_sqlite3.slice(0, better_sqlite3.lastIndexOf("node_modules")), "node_modules/better-sqlite3" ); const better_sqlite3_node = path.join( better_sqlite3_root, "build/Release", options.better_sqlite3_node as string ); const better_sqlite3_copy = path.join(output, options.better_sqlite3_node as string); if (!fs.existsSync(better_sqlite3_node)) { throw new Error(`${TAG} Can not found "${better_sqlite3_node}".`); } if (!fs.existsSync(output)) { fs.mkdirSync(output, { recursive: true }); } fs.copyFileSync(better_sqlite3_node, better_sqlite3_copy); /** `dist-native/better_sqlite3.node` */ const BETTER_SQLITE3_BINDING = better_sqlite3_copy.replace(resolvedRoot + "/", ""); fs.writeFileSync(path.join(resolvedRoot, ".env"), `VITE_BETTER_SQLITE3_BINDING=${BETTER_SQLITE3_BINDING}`); console.log(TAG, `binding to ${BETTER_SQLITE3_BINDING}`); } }; }
// 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 in the Renderer process. Wrapping them into a function. obj[key] = function (...args: any) { return value.call(obj, ...args); }; } else { obj[key] = value; } } return obj; }
// `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(true); } }); } }); }
// --------- 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.innerHTML = style; oDiv.className = "app-loading-wrap"; oDiv.innerHTML = `<div class="${className}">${dom}</div>`; return { appendLoading() { safeDOM.append(document.head, oStyle); safeDOM.append(document.body, oDiv); }, async removeLoading() { safeDOM.append(document.head, oStyle2); setTimeout(() => { safeDOM.remove(document.head, oStyle); safeDOM.remove(document.head, oStyle2); safeDOM.remove(document.body, oDiv); }, 1200); } }; }
/** * 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 ? 1 : 0]); await analysisTheirTeam(); await window.ipcRenderer.invoke(Handle.setFriendScoreMsg, generateAnalysisMsg(myTeam.value)); await window.ipcRenderer.invoke(Handle.setTheirScoreMsg, generateAnalysisMsg(theirTeam.value)); theirTeamIsSuck.value = false; theirTeamUpInfo.value = await analysisTeamUpInfo(theirTeam.value); //如果对面5黑,并且都是隐藏生涯,就判断是胜率队 if ( currentGameMode.value === "aram" && theirTeamUpInfo.value?.[0]?.length === 5 && theirTeam.value.filter((m) => m.summonerInfo?.privacy === "PRIVATE")?.length === 5 ) { new window.Notification("胜率队检测", { body: "对方为胜率队" }).onclick = async () => { await window.ipcRenderer.invoke(Handle.showMainWindow); await router.push({ name: "inGame", params: { showAnalysis: "true" } }); }; theirTeamIsSuck.value = true; } else if (theirTeamUpInfo.value.length != 0) { if (import.meta.env.DEV) { let i = 1; const msg = theirTeamUpInfo.value .map( (t) => `组队${i++}: ${t .map((puuid) => theirTeam.value.find((tm) => tm.puuid === puuid)?.summonerName) .join("\t")}` ) .join("\n"); console.log("对面组队信息", msg); } new window.Notification("对面存在开黑组队", { body: "跳转对局分析查看" }).onclick = async () => { await window.ipcRenderer.invoke(Handle.showMainWindow); await router.push({ name: "inGame", params: { showAnalysis: "true" } }); }; } }
//更新队伍信息
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 ex.buildCodeFrameError( `An error occurred when evaluating the expression: > ${value.message}. Make sure you are not using a browser or Node specific API and all the variables are available in static context. Linaria have to extract pieces of your code to resolve the interpolated values. Defining styled component or class will not work inside: - function, - class, - method, - loop, because it cannot be statically determined in which context you use them. That's why some variables may be not defined during evaluation. ` ); } if (checker(value)) { return; } const stringified = typeof value === 'object' ? JSON.stringify(value) : String(value); throw ex.buildCodeFrameError( `The expression evaluated to '${stringified}', which is probably a mistake. If you want it to be inserted into CSS, explicitly cast or transform the value to a string, e.g. - 'String(${source})'.` ); }
// 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] = Entrypoint.innerCreate( services, parent ? { evaluated: parent.evaluated, log: parent.log, name: parent.name, parents: parent.parents, seqId: parent.seqId, } : null, name, only, loadedCode ); if (status !== 'cached') { cache.add('entrypoints', name, entrypoint); } return status === 'loop' ? 'loop' : 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 new one and all cached results for it will be invalidated. * It can happen if the file was changed and the watcher notified us about it, or we received a new version * of the file from a loader whereas the previous one was loaded from the filesystem. * The new entrypoint will be returned. * 2. If `only` is subset of the existing entrypoint's `only`, the existing entrypoint will be returned. * 3. If `only` is superset of the existing entrypoint's `only`, the existing entrypoint will be superseded and the new one will be returned. * 4. If a loop is detected, 'ignored' will be returned, the existing entrypoint will be superseded or not depending on the `only` value. */
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.get('expression'); if (!expression.isCallExpression()) return; const callee = expression.get('callee'); const args = expression.get('arguments'); if (!callee.isFunctionExpression() || args.length !== 1) return; const [arg] = args; if (arg.isLogicalExpression({ operator: '||' })) { referenceAll(arg); } }, }); }
// @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 import('./init/index.js'); await init(options); break; case 'preview': const { preview } = await import('./preview/index.js'); await preview(options); break; case 'stdout': const { stdout } = await import('./stdout/index.js'); await stdout(options); break; case 'sync': const { sync } = await import('./sync/index.js'); await sync(options); break; default: await showHelp(); break; } } catch (e) { /** Filter out parseArgs errors (invalid/unknown option) and instead show help */ if (e instanceof TypeError && e?.stack?.includes('ERR_PARSE_ARGS')) await showHelp(); else throw e; } }
/** 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(obj); } } }
/** 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<string, any>) => this.searchFiles(iterable, this.addPropsCallback(props)); } let defaultProps: { name: string; value: any; type: PropertyTypes }[]; if (!this.settings.defaultPropPath) { defaultProps = [{ name: "", value: "", type: "text" }]; } else { try { const file = this.app.vault.getAbstractFileByPath( `${this.settings.defaultPropPath}.md` ); let tmp = this.readYamlProperties(file as TFile); if (tmp === undefined) throw Error("Undefined path."); defaultProps = tmp; } catch (e) { new Notice( `${e}. Check if you entered a valid path in the Default Props File setting.`, 10000 ); defaultProps = []; } } new PropModal( this.app, iterateFunc, this.settings.overwrite, this.settings.delimiter, defaultProps, this.changeOverwrite.bind(this) ).open(); }
/** 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)); } else { names = await this.getPropsFromFiles(iterable, new Set()); iterateFunc = (props: string[]) => this.searchFiles(iterable, this.removePropsCallback(props)); } if (names.length === 0) { new Notice("No properties to remove", 4000); return; } const sortedNames = [...names].sort((a, b) => a.toLowerCase() > b.toLowerCase() ? 1 : -1 ); new RemoveModal(this.app, sortedNames, iterateFunc).open(); }
/** 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.metadataCache.getAllPropertyInfos(); let result: { name: string; value: any; type: PropertyTypes }[] = []; for (let [key, value] of Object.entries(frontmatter)) { const keyLower = key.toLowerCase(); const obj = { name: key, value: value, type: allPropsWithType[keyLower].type, }; result.push(obj); } return result; }
/** 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