All files / src/node-to-fsa NodeFileSystemWritableFileStream.ts

84.26% Statements 75/89
60.52% Branches 23/38
100% Functions 11/11
97.22% Lines 70/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 18411x                           11x           1011x 1011x 1011x   242x   1011x 242x 287x 287x 287x 242x   45x       1011x 1011x 1011x                                         11x       1005x 1005x     1005x 1005x   1005x 1005x 1005x 1005x 1005x     1007x 1007x 1007x 1007x     1007x 1007x     1004x 1004x 1004x 1004x 1004x     1x 1x 1x 1x 1x     1005x                 256x               6x 6x 6x 6x 6x       1007x 1007x 1007x   1007x                   1012x 1012x   7x     1005x 1005x       281x   724x 467x   257x 257x   252x 252x     3x 3x 3x     2x 2x                          
import { Buffer } from '../internal/buffer';
import type { Data, FileSystemWritableFileStreamParams, IFileSystemWritableFileStream } from '../fsa/types';
import type { IFileHandle } from '../node/types/misc';
import type { NodeFsaFs } from './types';
 
/**
 * When Chrome writes to the file, it creates a copy of the file with extension
 * `.crswap` and then replaces the original file with the copy only when the
 * `close()` method is called. If the `abort()` method is called, the `.crswap`
 * file is deleted.
 *
 * If a file name with with extension `.crswap` is already taken, it
 * creates a new swap file with extension `.1.crswap` and so on.
 */
export const createSwapFile = async (
  fs: NodeFsaFs,
  path: string,
  keepExistingData: boolean,
): Promise<[handle: IFileHandle, path: string]> => {
  let handle: undefined | IFileHandle;
  let swapPath: string = path + '.crswap';
  try {
    handle = await fs.promises.open(swapPath, 'ax');
  } catch (error) {
    Iif (!error || typeof error !== 'object' || error.code !== 'EEXIST') throw error;
  }
  if (!handle) {
    for (let i = 1; i < 1000; i++) {
      try {
        swapPath = `${path}.${i}.crswap`;
        handle = await fs.promises.open(swapPath, 'ax');
        break;
      } catch (error) {
        Iif (!error || typeof error !== 'object' || error.code !== 'EEXIST') throw error;
      }
    }
  }
  Iif (!handle) throw new Error(`Could not create a swap file for "${path}".`);
  if (keepExistingData) await fs.promises.copyFile(path, swapPath, fs.constants.COPYFILE_FICLONE);
  return [handle, swapPath];
};
 
interface SwapFile {
  /** Swap file full path name. */
  path: string;
  /** Seek offset in the file. */
  offset: number;
  /** Node.js open FileHandle. */
  handle?: IFileHandle;
  /** Resolves when swap file is ready for operations. */
  ready?: Promise<void>;
}
 
/**
 * Is a WritableStream object with additional convenience methods, which
 * operates on a single file on disk. The interface is accessed through the
 * `FileSystemFileHandle.createWritable()` method.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream
 */
export class NodeFileSystemWritableFileStream extends WritableStream implements IFileSystemWritableFileStream {
  protected readonly swap: SwapFile;
 
  constructor(
    protected readonly fs: NodeFsaFs,
    protected readonly path: string,
    keepExistingData: boolean,
  ) {
    const swap: SwapFile = { handle: undefined, path: '', offset: 0 };
    super({
      async start() {
        const promise = createSwapFile(fs, path, keepExistingData);
        swap.ready = promise.then(() => undefined);
        const [handle, swapPath] = await promise;
        swap.handle = handle;
        swap.path = swapPath;
      },
      async write(chunk: Data) {
        await swap.ready;
        const handle = swap.handle;
        Iif (!handle) throw new Error('Invalid state');
        const buffer = Buffer.from(
          typeof chunk === 'string' ? chunk : chunk instanceof Blob ? await chunk.arrayBuffer() : chunk,
        );
        const { bytesWritten } = await handle.write(buffer, 0, buffer.length, swap.offset);
        swap.offset += bytesWritten;
      },
      async close() {
        await swap.ready;
        const handle = swap.handle;
        Iif (!handle) return;
        await handle.close();
        await fs.promises.rename(swap.path, path);
      },
      async abort() {
        await swap.ready;
        const handle = swap.handle;
        Iif (!handle) return;
        await handle.close();
        await fs.promises.unlink(swap.path);
      },
    });
    this.swap = swap;
  }
 
  /**
   * @sse https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/seek
   * @param position An `unsigned long` describing the byte position from the top
   *                 (beginning) of the file.
   */
  public async seek(position: number): Promise<void> {
    this.swap.offset = position;
  }
 
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/truncate
   * @param size An `unsigned long` of the amount of bytes to resize the stream to.
   */
  public async truncate(size: number): Promise<void> {
    await this.swap.ready;
    const handle = this.swap.handle;
    Iif (!handle) throw new Error('Invalid state');
    await handle.truncate(size);
    Iif (this.swap.offset > size) this.swap.offset = size;
  }
 
  protected async writeBase(chunk: Data): Promise<void> {
    const writer = this.getWriter();
    try {
      await writer.write(chunk);
    } finally {
      writer.releaseLock();
    }
  }
 
  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream/write
   */
  public async write(chunk: Data): Promise<void>;
  public async write(params: FileSystemWritableFileStreamParams): Promise<void>;
  public async write(params): Promise<void> {
    Iif (!params) throw new TypeError('Missing required argument: params');
    switch (typeof params) {
      case 'string': {
        return this.writeBase(params);
      }
      case 'object': {
        const constructor = params.constructor;
        switch (constructor) {
          case ArrayBuffer:
          case Blob:
          case DataView:
            return this.writeBase(params);
          default: {
            if (ArrayBuffer.isView(params)) {
              return this.writeBase(params);
            } else {
              const options = params as FileSystemWritableFileStreamParams;
              switch (options.type) {
                case 'write': {
                  if (typeof options.position === 'number') await this.seek(options.position);
                  return this.writeBase(params.data);
                }
                case 'truncate': {
                  Iif (typeof params.size !== 'number') throw new TypeError('Missing required argument: size');
                  Iif (this.swap.offset > params.size) this.swap.offset = params.size;
                  return this.truncate(params.size);
                }
                case 'seek':
                  Iif (typeof params.position !== 'number') throw new TypeError('Missing required argument: position');
                  return this.seek(params.position);
                default:
                  throw new TypeError('Invalid argument: params');
              }
            }
          }
        }
      }
      default:
        throw new TypeError('Invalid argument: params');
    }
  }
}