<commit_before>import Dexie, { liveQuery, Subscription, Table } from 'dexie';
import './extend-dexie-interface';
import { BehaviorSubject, from, Observable, Subject } from 'rxjs';
import {
  createIdGenerationMiddleware,
  generateTablePrefix
} from './middlewares/createIdGenerationMiddleware';
import { DexieCloudOptions } from './DexieCloudOptions';
//import { dexieCloudSyncProtocol } from "./dexieCloudSyncProtocol";
import { overrideParseStoresSpec } from './overrideParseStoresSpec';
import { DexieCloudDB } from './db/DexieCloudDB';
import { UserLogin } from './db/entities/UserLogin';
import { UNAUTHORIZED_USER } from './authentication/UNAUTHORIZED_USER';
import { login } from './authentication/login';
import {
  getDbNameFromDbUrl,
  OTPTokenRequest,
  TokenFinalResponse,
  TokenOtpSentResponse,
  TokenResponse
} from 'dexie-cloud-common';
import { LoginState } from './types/LoginState';
import { SyncState } from './types/SyncState';
import { verifySchema } from './verifySchema';
import { throwVersionIncrementNeeded } from './helpers/throwVersionIncrementNeeded';
import { performInitialSync } from './performInitialSync';
import { LocalSyncWorker } from './sync/LocalSyncWorker';
import { dbOnClosed } from './helpers/dbOnClosed';
import { IS_SERVICE_WORKER } from './helpers/IS_SERVICE_WORKER';
import { authenticate, loadAccessToken } from './authentication/authenticate';
import { createMutationTrackingMiddleware } from './middlewares/createMutationTrackingMiddleware';
import { updateSchemaFromOptions } from './updateSchemaFromOptions';
import {
  registerPeriodicSyncEvent,
  registerSyncEvent
} from './sync/registerSyncEvent';
import { createImplicitPropSetterMiddleware } from './middlewares/createImplicitPropSetterMiddleware';
import { sync } from './sync/sync';
import { filter, map, take } from 'rxjs/operators';
import { triggerSync } from './sync/triggerSync';
import { DexieCloudSyncOptions } from './extend-dexie-interface';
import { isSyncNeeded } from './sync/isSyncNeeded';
import { connectWebSocket } from './sync/connectWebSocket';

export { DexieCloudTable } from './extend-dexie-interface';

export function dexieCloud(dexie: Dexie) {
  const origIdbName = dexie.name;
  //
  //
  //
  const currentUserEmitter = new BehaviorSubject(UNAUTHORIZED_USER);
  const subscriptions: Subscription[] = [];

  // local sync worker - used when there's no service worker.
  let localSyncWorker: { start: () => void; stop: () => void } | null = null;
  dexie.on(
    'ready',
    async (dexie: Dexie) => {
      const db = DexieCloudDB(dexie);
      //verifyConfig(db.cloud.options); Not needed (yet at least!)
      // Verify the user has allowed version increment.
      if (!db.tables.every((table) => table.core)) {
        throwVersionIncrementNeeded();
      }

      const initiallySynced = await db.transaction(
        'rw',
        db.$syncState,
        async () => {
          const { options, schema } = db.cloud;
          const [persistedOptions, persistedSchema, persistedSyncState] =
            await Promise.all([
              db.getOptions(),
              db.getSchema(),
              db.getPersistedSyncState()
            ]);
          if (!options) {
            // Options not specified programatically (use case for SW!)
            // Take persisted options:
            db.cloud.options = persistedOptions || null;
          } else if (
            !persistedOptions ||
            JSON.stringify(persistedOptions) !== JSON.stringify(options)
          ) {
            // Update persisted options:
            await db.$syncState.put(options, 'options');
          }
          if (
            db.cloud.options?.usingServiceWorker &&
            !('serviceWorker' in navigator)
          ) {
            // Configured to use service worker, but this browser doesn't support it.
            // Act as if usingServiceWorker is configured falsy:
            db.cloud.options.usingServiceWorker = false;
          }
          updateSchemaFromOptions(schema, db.cloud.options);
          updateSchemaFromOptions(persistedSchema, db.cloud.options);
          if (!schema) {
            // Database opened dynamically (use case for SW!)
            // Take persisted schema:
            db.cloud.schema = persistedSchema || null;
          } else if (
            !persistedSchema ||
            JSON.stringify(persistedSchema) !== JSON.stringify(schema)
          ) {
            // Update persisted schema (but don't overwrite table prefixes)
            const newPersistedSchema = persistedSchema || {};
            for (const [table, tblSchema] of Object.entries(schema)) {
              const newTblSchema = newPersistedSchema[table];
              if (!newTblSchema) {
                newPersistedSchema[table] = {...tblSchema};
              } else {
                newTblSchema.markedForSync = tblSchema.markedForSync;
                tblSchema.deleted = newTblSchema.deleted;
                newTblSchema.generatedGlobalId = tblSchema.generatedGlobalId;
              }
            }
            await db.$syncState.put(newPersistedSchema, 'schema');

            // Make sure persisted table prefixes are being used instead of computed ones:
            // Let's assign all props as the newPersistedSchems should be what we should be working with.
            Object.assign(schema, newPersistedSchema);
          }
          return persistedSyncState?.initiallySynced;
        }
      );

      if (initiallySynced) {
        // @ts-ignore
        db.setInitiallySynced(true);
      }

      verifySchema(db);

      if (db.cloud.options?.databaseUrl && !initiallySynced) {
        await performInitialSync(db, db.cloud.options, db.cloud.schema!);
        db.setInitiallySynced(true);
      }

      // Manage CurrentUser observable:
      subscriptions.push(
        liveQuery(() => db.getCurrentUser()).subscribe(currentUserEmitter)
      );

      // HERE: If requireAuth, do athentication now.
      if (db.cloud.options?.requireAuth) {<commit_msg>Removed ts-ignore comment<commit_after>import Dexie, { liveQuery, Subscription, Table } from 'dexie';
import './extend-dexie-interface';
import { BehaviorSubject, from, Observable, Subject } from 'rxjs';
import {
  createIdGenerationMiddleware,
  generateTablePrefix
} from './middlewares/createIdGenerationMiddleware';
import { DexieCloudOptions } from './DexieCloudOptions';
//import { dexieCloudSyncProtocol } from "./dexieCloudSyncProtocol";
import { overrideParseStoresSpec } from './overrideParseStoresSpec';
import { DexieCloudDB } from './db/DexieCloudDB';
import { UserLogin } from './db/entities/UserLogin';
import { UNAUTHORIZED_USER } from './authentication/UNAUTHORIZED_USER';
import { login } from './authentication/login';
import {
  getDbNameFromDbUrl,
  OTPTokenRequest,
  TokenFinalResponse,
  TokenOtpSentResponse,
  TokenResponse
} from 'dexie-cloud-common';
import { LoginState } from './types/LoginState';
import { SyncState } from './types/SyncState';
import { verifySchema } from './verifySchema';
import { throwVersionIncrementNeeded } from './helpers/throwVersionIncrementNeeded';
import { performInitialSync } from './performInitialSync';
import { LocalSyncWorker } from './sync/LocalSyncWorker';
import { dbOnClosed } from './helpers/dbOnClosed';
import { IS_SERVICE_WORKER } from './helpers/IS_SERVICE_WORKER';
import { authenticate, loadAccessToken } from './authentication/authenticate';
import { createMutationTrackingMiddleware } from './middlewares/createMutationTrackingMiddleware';
import { updateSchemaFromOptions } from './updateSchemaFromOptions';
import {
  registerPeriodicSyncEvent,
  registerSyncEvent
} from './sync/registerSyncEvent';
import { createImplicitPropSetterMiddleware } from './middlewares/createImplicitPropSetterMiddleware';
import { sync } from './sync/sync';
import { filter, map, take } from 'rxjs/operators';
import { triggerSync } from './sync/triggerSync';
import { DexieCloudSyncOptions } from './extend-dexie-interface';
import { isSyncNeeded } from './sync/isSyncNeeded';
import { connectWebSocket } from './sync/connectWebSocket';

export { DexieCloudTable } from './extend-dexie-interface';

export function dexieCloud(dexie: Dexie) {
  const origIdbName = dexie.name;
  //
  //
  //
  const currentUserEmitter = new BehaviorSubject(UNAUTHORIZED_USER);
  const subscriptions: Subscription[] = [];

  // local sync worker - used when there's no service worker.
  let localSyncWorker: { start: () => void; stop: () => void } | null = null;
  dexie.on(
    'ready',
    async (dexie: Dexie) => {
      const db = DexieCloudDB(dexie);
      //verifyConfig(db.cloud.options); Not needed (yet at least!)
      // Verify the user has allowed version increment.
      if (!db.tables.every((table) => table.core)) {
        throwVersionIncrementNeeded();
      }

      const initiallySynced = await db.transaction(
        'rw',
        db.$syncState,
        async () => {
          const { options, schema } = db.cloud;
          const [persistedOptions, persistedSchema, persistedSyncState] =
            await Promise.all([
              db.getOptions(),
              db.getSchema(),
              db.getPersistedSyncState()
            ]);
          if (!options) {
            // Options not specified programatically (use case for SW!)
            // Take persisted options:
            db.cloud.options = persistedOptions || null;
          } else if (
            !persistedOptions ||
            JSON.stringify(persistedOptions) !== JSON.stringify(options)
          ) {
            // Update persisted options:
            await db.$syncState.put(options, 'options');
          }
          if (
            db.cloud.options?.usingServiceWorker &&
            !('serviceWorker' in navigator)
          ) {
            // Configured to use service worker, but this browser doesn't support it.
            // Act as if usingServiceWorker is configured falsy:
            db.cloud.options.usingServiceWorker = false;
          }
          updateSchemaFromOptions(schema, db.cloud.options);
          updateSchemaFromOptions(persistedSchema, db.cloud.options);
          if (!schema) {
            // Database opened dynamically (use case for SW!)
            // Take persisted schema:
            db.cloud.schema = persistedSchema || null;
          } else if (
            !persistedSchema ||
            JSON.stringify(persistedSchema) !== JSON.stringify(schema)
          ) {
            // Update persisted schema (but don't overwrite table prefixes)
            const newPersistedSchema = persistedSchema || {};
            for (const [table, tblSchema] of Object.entries(schema)) {
              const newTblSchema = newPersistedSchema[table];
              if (!newTblSchema) {
                newPersistedSchema[table] = {...tblSchema};
              } else {
                newTblSchema.markedForSync = tblSchema.markedForSync;
                tblSchema.deleted = newTblSchema.deleted;
                newTblSchema.generatedGlobalId = tblSchema.generatedGlobalId;
              }
            }
            await db.$syncState.put(newPersistedSchema, 'schema');

            // Make sure persisted table prefixes are being used instead of computed ones:
            // Let's assign all props as the newPersistedSchems should be what we should be working with.
            Object.assign(schema, newPersistedSchema);
          }
          return persistedSyncState?.initiallySynced;
        }
      );

      if (initiallySynced) {
        db.setInitiallySynced(true);
      }

      verifySchema(db);

      if (db.cloud.options?.databaseUrl && !initiallySynced) {
        await performInitialSync(db, db.cloud.options, db.cloud.schema!);
        db.setInitiallySynced(true);
      }

      // Manage CurrentUser observable:
      subscriptions.push(
        liveQuery(() => db.getCurrentUser()).subscribe(currentUserEmitter)
      );

      // HERE: If requireAuth, do athentication now.
      if (db.cloud.options?.requireAuth) {
{'fraction_non_alphanumeric': 0.11100947946116747, 'fraction_numerical': 0.0, 'mean_word_length': 2.722376973073352, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1074423', 'n_tokens_mistral': 3271, 'n_tokens_neox': 3184, 'n_words': 771}