app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

listing-continuity.ts (7100B)


      1 // HC_TEST_ONLY_QUALIFICATION_PORT: actual browser owners/native acknowledgments.
      2 import * as editorApi from '../../../src/lib/publishing/listing-editor.ts';
      3 import {
      4   createFixture as baseFixture,
      5   blank,
      6   inspectNative,
      7   nativeObservation
      8 } from './listing-editor.ts';
      9 import { createFixture as operationFixture } from './listing-operation-view.ts';
     10 import {
     11   createIdentityViewContext,
     12   mountIdentityView,
     13   connectIdentityView,
     14   disconnectIdentityView,
     15   closeIdentityView
     16 } from '../../../src/lib/runtime/view-context.ts';
     17 import type { PublicDraftForm } from '../../../src/lib/contracts/local-records.ts';
     18 export { blank, inspectNative, nativeObservation };
     19 export async function createFixture() {
     20   const base = await baseFixture(),
     21     context = createIdentityViewContext();
     22   mountIdentityView(context);
     23   await connectIdentityView(context);
     24   let editor: editorApi.ListingEditor | undefined;
     25   let operation: Awaited<ReturnType<typeof operationFixture>> | undefined;
     26   return {
     27     inspect: base.inspect,
     28     counts: base.counts,
     29     async open(route: editorApi.ListingEditorRoute) {
     30       const result = await editorApi.openListingEditor(context, route);
     31       if (result.status === 'ready') editor = result.editor;
     32       return result.status === 'ready'
     33         ? {
     34             status: result.status,
     35             snapshot: editorApi.listingEditorSnapshot(result.editor)
     36           }
     37         : result;
     38     },
     39     snapshot: () => editor && editorApi.listingEditorSnapshot(editor),
     40     edit: (form: PublicDraftForm) =>
     41       editor
     42         ? editorApi.editListingEditor(editor, form)
     43         : Promise.resolve(false),
     44     async saveClose(copied = false) {
     45       const action: unknown = Reflect.get(
     46         editorApi,
     47         'saveAndCloseListingEditor'
     48       );
     49       if (typeof action !== 'function')
     50         throw Error(
     51           'HCP116 save-close producer absent; no passing result inferred'
     52         );
     53       return editor
     54         ? await (
     55             action as (value: editorApi.ListingEditor) => Promise<boolean>
     56           )(copied ? { ...editor } : editor)
     57         : false;
     58     },
     59     disconnect() {
     60       disconnectIdentityView(context);
     61     },
     62     async captured(unknown = false) {
     63       operation = await operationFixture();
     64       if (unknown) {
     65         await operation.holdSigning();
     66         await operation.stopSigning();
     67       } else if ((await operation.signed()) !== 'prepared')
     68         throw Error('actual signature failed');
     69       const row = await operation.row();
     70       if (row.source.type !== 'draft')
     71         throw Error('actual source draft missing');
     72       disconnectIdentityView(context);
     73       await connectIdentityView(context);
     74       return {
     75         draftId: row.source.id,
     76         command: row.id,
     77         row,
     78         signs: operation.counts()
     79       };
     80     },
     81     async close() {
     82       if (editor) editorApi.closeListingEditor(editor);
     83       closeIdentityView(context);
     84       operation?.close();
     85       await base.close();
     86     }
     87   };
     88 }
     89 // Abort actual native transactions after a genuine successful put; no fake event/result.
     90 export function abortDraftWrites() {
     91   const descriptor = Object.getOwnPropertyDescriptor(
     92     IDBObjectStore.prototype,
     93     'put'
     94   )!;
     95   const original = descriptor.value as IDBObjectStore['put'];
     96   let enabled = true,
     97     aborts = 0;
     98   const ids: string[] = [];
     99   Object.defineProperty(IDBObjectStore.prototype, 'put', {
    100     ...descriptor,
    101     value: function (this: IDBObjectStore, value: unknown, key?: IDBValidKey) {
    102       const request = original.call(this, value, key),
    103         transaction = this.transaction;
    104       if (
    105         enabled &&
    106         this.name === 'public_drafts' &&
    107         transaction.mode === 'readwrite'
    108       ) {
    109         if (
    110           value &&
    111           typeof value === 'object' &&
    112           'id' in value &&
    113           typeof value.id === 'string'
    114         )
    115           ids.push(value.id);
    116         request.addEventListener('success', () => {
    117           if (enabled) {
    118             aborts++;
    119             transaction.abort();
    120           }
    121         });
    122       }
    123       return request;
    124     }
    125   });
    126   return {
    127     state: () => ({ aborts, ids: ids.slice() }),
    128     restore() {
    129       enabled = false;
    130       Object.defineProperty(IDBObjectStore.prototype, 'put', descriptor);
    131     }
    132   };
    133 }
    134 // Lose only original application request ACK callbacks after an actual committed
    135 // put and its genuine readback. Native completion events/results are untouched.
    136 export function unknownDraftAcknowledgment() {
    137   const putDescriptor = Object.getOwnPropertyDescriptor(
    138     IDBObjectStore.prototype,
    139     'put'
    140   )!;
    141   const originalPut = putDescriptor.value as IDBObjectStore['put'];
    142   const ownListener = Object.getOwnPropertyDescriptor(
    143     IDBRequest.prototype,
    144     'addEventListener'
    145   );
    146   const listenerDescriptor =
    147     ownListener ??
    148     Object.getOwnPropertyDescriptor(EventTarget.prototype, 'addEventListener')!;
    149   const originalListener =
    150     listenerDescriptor.value as IDBRequest['addEventListener'];
    151   const held: {
    152     target: IDBRequest;
    153     event: Event;
    154     listener: EventListenerOrEventListenerObject;
    155   }[] = [];
    156   let enabled = true,
    157     putSubmitted = false,
    158     puts = 0;
    159   Object.defineProperty(IDBObjectStore.prototype, 'put', {
    160     ...putDescriptor,
    161     value: function (this: IDBObjectStore, value: unknown, key?: IDBValidKey) {
    162       if (
    163         this.name === 'public_drafts' &&
    164         this.transaction.mode === 'readwrite'
    165       ) {
    166         putSubmitted = true;
    167         puts++;
    168       }
    169       return originalPut.call(this, value, key);
    170     }
    171   });
    172   Object.defineProperty(IDBRequest.prototype, 'addEventListener', {
    173     configurable: true,
    174     writable: true,
    175     value: function (
    176       this: IDBRequest,
    177       type: string,
    178       listener: EventListenerOrEventListenerObject | null,
    179       options?: AddEventListenerOptions | boolean
    180     ) {
    181       if (!listener) return;
    182       return originalListener.call(
    183         this,
    184         type,
    185         function (event: Event) {
    186           const target = event.currentTarget as IDBRequest,
    187             source = target.source;
    188           if (
    189             enabled &&
    190             putSubmitted &&
    191             type === 'success' &&
    192             source instanceof IDBObjectStore &&
    193             source.name === 'public_drafts'
    194           )
    195             held.push({ target, event, listener });
    196           else if (typeof listener === 'function') listener.call(target, event);
    197           else listener.handleEvent(event);
    198         },
    199         options
    200       );
    201     }
    202   });
    203   return {
    204     state: () => ({ puts, held: held.length }),
    205     release() {
    206       enabled = false;
    207       Object.defineProperty(IDBObjectStore.prototype, 'put', putDescriptor);
    208       if (ownListener)
    209         Object.defineProperty(
    210           IDBRequest.prototype,
    211           'addEventListener',
    212           ownListener
    213         );
    214       else Reflect.deleteProperty(IDBRequest.prototype, 'addEventListener');
    215       for (const row of held.splice(0))
    216         if (typeof row.listener === 'function')
    217           row.listener.call(row.target, row.event);
    218         else row.listener.handleEvent(row.event);
    219     }
    220   };
    221 }