@arbidocs/react 0.4.82 → 0.4.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -460,10 +460,28 @@ declare function useDocumentSignatures(documentId: string | null | undefined, en
460
460
  certificate_url?: string | null;
461
461
  signatures: components["schemas"]["SignatureRecord"][];
462
462
  }>, Error>;
463
+ /**
464
+ * Why the server would not sign: the PDF of a Word or text document is still being rendered
465
+ * (`preparing`, worth another try in a moment), or the version on screen is no longer the current
466
+ * one (`stale`: only the current version can be signed, so the signer reopens it).
467
+ */
468
+ type SigningErrorReason = 'preparing' | 'stale' | 'failed';
469
+ declare class SigningError extends Error {
470
+ readonly reason: SigningErrorReason;
471
+ constructor(message: string, reason: SigningErrorReason);
472
+ }
463
473
  interface SignDocumentVars {
464
474
  documentId: string;
465
- /** The PDF bytes the viewer is showing: the signer signs exactly these. */
475
+ /**
476
+ * The PDF bytes the viewer is showing (`GET /view?version=`, never the original's download): the
477
+ * signer signs exactly these.
478
+ */
466
479
  pdfBlob: Blob;
480
+ /**
481
+ * The version `pdfBlob` is of. The server signs only the current version and refuses
482
+ * (`SigningError` `stale`) when this one has been superseded. Omitted = the current version.
483
+ */
484
+ version?: number;
467
485
  email: string;
468
486
  password: string;
469
487
  signer: SignerDetails;
@@ -481,7 +499,7 @@ interface SignDocumentVars {
481
499
  * with `includeDate`, the date; anyone can click it to open its certificate. A role, a firm or a
482
500
  * place go on the page as ordinary annotation text, which is not part of the signature.
483
501
  */
484
- declare function signDocument(client: DocumentToolsClient, deploymentDomain: string, { documentId, pdfBlob, email, password, signer, appearance, includeDate, }: SignDocumentVars): Promise<SignDocumentResponse>;
502
+ declare function signDocument(client: DocumentToolsClient, deploymentDomain: string, { documentId, pdfBlob, email, password, signer, appearance, includeDate, version, }: SignDocumentVars): Promise<SignDocumentResponse>;
485
503
  /** The signing mutation. On success the host hears the document changed (`'signed'`). */
486
504
  declare function useSignDocument(): _tanstack_react_query.UseMutationResult<{
487
505
  doc_ext_id: string;
@@ -519,4 +537,4 @@ type CopyMatch = {
519
537
  /** Compare a file with the signed PDF and its signed revisions. Hashed here; nothing is uploaded. */
520
538
  declare function matchSignedCopy(file: Blob, verification: Pick<SignatureVerification, 'document_sha256' | 'signatures'>): Promise<CopyMatch>;
521
539
 
522
- export { type AnnotatableState, type BuildProductionOptions, type BuiltProduction, type CopyMatch, type DocumentChange, DocumentFetchError, type DocumentFetchOptions, type DocumentToolsClient, type DocumentToolsEnvironment, type DocumentToolsNoticeKind, type DocumentToolsNoticeOptions, type DocumentToolsNotify, DocumentToolsProvider, type DocumentToolsProviderProps, type DocumentToolsUser, type DocumentUploadQuery, type DocumentUploadRequest, type FrozenCopySource, LEGACY_LAYER_PREFIX, type LegacyPrompt, MAX_MERGE_ATTEMPTS, type MarkupDocument, MarkupDownloadError, type MarkupSnapshot, type MarkupStore, MarkupStoreError, type MarkupStoreOptions, type OlderMarkupNote, PRODUCTIONS_FOLDER, type ProductionSource, type ProductionUpload, type ResolvedDocumentToolsEnvironment, SIGNED_LOCKED_REASON, SIGNED_UNCHANGED, type SignDocumentResponse, type SignDocumentVars, type SignatureAppearance, type SignatureRecord, type SignatureStatusResponse, type SignatureVerification, SignatureVerificationError, type SignerDetails, VERIFY_PATH, type VerifiedSignature, type VersionInfo, addToMarkup, buildProduction, canAnnotate, certificateLink, clientUpload, copyOpenThreads, createMarkupStore, currentHasMarkup, defaultCertificateUrl, downloadBlob, fetchDocumentFile, fetchDocumentPdf, fetchDocumentSignatures, fetchMarkupPdf, fetchProductionPdf, fetchSignatureVerification, forgetLegacyLayer, frozenCopyName, hasNoRendition, intentText, isLegibleSignatureBox, isPdfDocument, isSignatureReference, isSignedVersion, marksByVersion, matchSignedCopy, migrateLegacyLayer, openThreadsOf, productionDocumentName, productionFileName, productionFolder, productionIndexCsv, productionTitle, readLegacyLayer, redactionLogName, saveProductionFiles, sha256Hex, signDocument, toAppearance, uploadFrozenCopy, uploadQueryString, useDocumentMarkup, useDocumentSignatures, useDocumentTools, useIsOnline, useOptionalDocumentTools, useSignDocument, useSignatureVerification, versionsWithMarkup };
540
+ export { type AnnotatableState, type BuildProductionOptions, type BuiltProduction, type CopyMatch, type DocumentChange, DocumentFetchError, type DocumentFetchOptions, type DocumentToolsClient, type DocumentToolsEnvironment, type DocumentToolsNoticeKind, type DocumentToolsNoticeOptions, type DocumentToolsNotify, DocumentToolsProvider, type DocumentToolsProviderProps, type DocumentToolsUser, type DocumentUploadQuery, type DocumentUploadRequest, type FrozenCopySource, LEGACY_LAYER_PREFIX, type LegacyPrompt, MAX_MERGE_ATTEMPTS, type MarkupDocument, MarkupDownloadError, type MarkupSnapshot, type MarkupStore, MarkupStoreError, type MarkupStoreOptions, type OlderMarkupNote, PRODUCTIONS_FOLDER, type ProductionSource, type ProductionUpload, type ResolvedDocumentToolsEnvironment, SIGNED_LOCKED_REASON, SIGNED_UNCHANGED, type SignDocumentResponse, type SignDocumentVars, type SignatureAppearance, type SignatureRecord, type SignatureStatusResponse, type SignatureVerification, SignatureVerificationError, type SignerDetails, SigningError, type SigningErrorReason, VERIFY_PATH, type VerifiedSignature, type VersionInfo, addToMarkup, buildProduction, canAnnotate, certificateLink, clientUpload, copyOpenThreads, createMarkupStore, currentHasMarkup, defaultCertificateUrl, downloadBlob, fetchDocumentFile, fetchDocumentPdf, fetchDocumentSignatures, fetchMarkupPdf, fetchProductionPdf, fetchSignatureVerification, forgetLegacyLayer, frozenCopyName, hasNoRendition, intentText, isLegibleSignatureBox, isPdfDocument, isSignatureReference, isSignedVersion, marksByVersion, matchSignedCopy, migrateLegacyLayer, openThreadsOf, productionDocumentName, productionFileName, productionFolder, productionIndexCsv, productionTitle, readLegacyLayer, redactionLogName, saveProductionFiles, sha256Hex, signDocument, toAppearance, uploadFrozenCopy, uploadQueryString, useDocumentMarkup, useDocumentSignatures, useDocumentTools, useIsOnline, useOptionalDocumentTools, useSignDocument, useSignatureVerification, versionsWithMarkup };
@@ -1,10 +1,10 @@
1
+ import { mergeLayers, AnnotationStoreOfflineError } from '../chunk-IHTBAY57.js';
2
+ import { parseLayer, emptyLayer, LAYER_SCHEMA_VERSION } from '../chunk-COWZGCL5.js';
1
3
  import { parseVersionRef } from '../chunk-HKUD2NZN.js';
2
4
  import '../chunk-G6FHNURH.js';
3
5
  import '../chunk-WUTL62MC.js';
4
- import { mergeLayers, AnnotationStoreOfflineError } from '../chunk-IHTBAY57.js';
5
- import { parseLayer, emptyLayer, LAYER_SCHEMA_VERSION } from '../chunk-COWZGCL5.js';
6
- import '../chunk-QRCMKEE6.js';
7
6
  import '../chunk-YNNAJJ5Z.js';
7
+ import '../chunk-QRCMKEE6.js';
8
8
  import '../chunk-47CCGUWR.js';
9
9
  import '../chunk-SN5YV6FF.js';
10
10
  import { useDeploymentDomain } from '../chunk-WBYNKFUO.js';
@@ -737,6 +737,26 @@ function useDocumentSignatures(documentId, enabled = true) {
737
737
  staleTime: 6e4
738
738
  });
739
739
  }
740
+ var SigningError = class extends Error {
741
+ reason;
742
+ constructor(message, reason) {
743
+ super(message);
744
+ this.name = "SigningError";
745
+ this.reason = reason;
746
+ }
747
+ };
748
+ function signingErrorReason(detail) {
749
+ if (/still being prepared/i.test(detail)) return "preparing";
750
+ if (/no longer the current version/i.test(detail)) return "stale";
751
+ return "failed";
752
+ }
753
+ function signingError(error, fallback) {
754
+ const detail = errorDetail(error, fallback);
755
+ return new SigningError(detail, signingErrorReason(detail));
756
+ }
757
+ var PREPARE_RETRIES = 3;
758
+ var PREPARE_RETRY_DELAY_MS = 1500;
759
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
740
760
  async function signDocument(client, deploymentDomain, {
741
761
  documentId,
742
762
  pdfBlob,
@@ -744,19 +764,24 @@ async function signDocument(client, deploymentDomain, {
744
764
  password,
745
765
  signer,
746
766
  appearance,
747
- includeDate = false
767
+ includeDate = false,
768
+ version
748
769
  }) {
749
770
  const path = { document_ext_id: documentId };
750
771
  const body = {
751
772
  signer: { name: signer.name },
752
773
  ...appearance ? { appearance } : {},
753
- include_date: includeDate
774
+ include_date: includeDate,
775
+ ...version ? { version } : {}
754
776
  };
755
- const prepared = await client.POST("/v1/document/{document_ext_id}/sign/prepare", {
756
- params: { path },
757
- body
758
- });
759
- if (!prepared.data) throw new Error(errorDetail(prepared.error, "Could not prepare signing"));
777
+ const prepare = () => client.POST("/v1/document/{document_ext_id}/sign/prepare", { params: { path }, body });
778
+ let prepared = await prepare();
779
+ for (let attempt = 0; !prepared.data && attempt < PREPARE_RETRIES; attempt++) {
780
+ if (signingError(prepared.error, "").reason !== "preparing") break;
781
+ await wait(PREPARE_RETRY_DELAY_MS);
782
+ prepared = await prepare();
783
+ }
784
+ if (!prepared.data) throw signingError(prepared.error, "Could not prepare signing");
760
785
  const { statement, intent, source_sha256, timestamp } = prepared.data;
761
786
  if (await sha256Hex(pdfBlob) !== source_sha256) {
762
787
  throw new Error("The document changed since it was opened. Reopen it and sign again.");
@@ -767,7 +792,7 @@ async function signDocument(client, deploymentDomain, {
767
792
  params: { path },
768
793
  body: { ...body, timestamp, signature: signMessage(statement, signingKeyPair.secretKey) }
769
794
  });
770
- if (!signed.data) throw new Error(errorDetail(signed.error, "Signing failed"));
795
+ if (!signed.data) throw signingError(signed.error, "Signing failed");
771
796
  return signed.data;
772
797
  }
773
798
  function useSignDocument() {
@@ -832,6 +857,6 @@ async function matchSignedCopy(file, verification) {
832
857
  return signature ? { kind: "earlier", signature } : { kind: "none" };
833
858
  }
834
859
 
835
- export { DocumentFetchError, DocumentToolsProvider, LEGACY_LAYER_PREFIX, MAX_MERGE_ATTEMPTS, MarkupDownloadError, MarkupStoreError, PRODUCTIONS_FOLDER, SIGNED_LOCKED_REASON, SIGNED_UNCHANGED, SignatureVerificationError, VERIFY_PATH, addToMarkup, buildProduction, canAnnotate, certificateLink, clientUpload, copyOpenThreads, createMarkupStore, currentHasMarkup, defaultCertificateUrl, downloadBlob, fetchDocumentFile, fetchDocumentPdf, fetchDocumentSignatures, fetchMarkupPdf, fetchProductionPdf, fetchSignatureVerification, forgetLegacyLayer, frozenCopyName, hasNoRendition, intentText, isLegibleSignatureBox, isPdfDocument, isSignatureReference, isSignedVersion, marksByVersion, matchSignedCopy, migrateLegacyLayer, openThreadsOf, productionDocumentName, productionFileName, productionFolder, productionIndexCsv, productionTitle, readLegacyLayer, redactionLogName, saveProductionFiles, sha256Hex, signDocument, toAppearance, uploadFrozenCopy, uploadQueryString, useDocumentMarkup, useDocumentSignatures, useDocumentTools, useIsOnline, useOptionalDocumentTools, useSignDocument, useSignatureVerification, versionsWithMarkup };
860
+ export { DocumentFetchError, DocumentToolsProvider, LEGACY_LAYER_PREFIX, MAX_MERGE_ATTEMPTS, MarkupDownloadError, MarkupStoreError, PRODUCTIONS_FOLDER, SIGNED_LOCKED_REASON, SIGNED_UNCHANGED, SignatureVerificationError, SigningError, VERIFY_PATH, addToMarkup, buildProduction, canAnnotate, certificateLink, clientUpload, copyOpenThreads, createMarkupStore, currentHasMarkup, defaultCertificateUrl, downloadBlob, fetchDocumentFile, fetchDocumentPdf, fetchDocumentSignatures, fetchMarkupPdf, fetchProductionPdf, fetchSignatureVerification, forgetLegacyLayer, frozenCopyName, hasNoRendition, intentText, isLegibleSignatureBox, isPdfDocument, isSignatureReference, isSignedVersion, marksByVersion, matchSignedCopy, migrateLegacyLayer, openThreadsOf, productionDocumentName, productionFileName, productionFolder, productionIndexCsv, productionTitle, readLegacyLayer, redactionLogName, saveProductionFiles, sha256Hex, signDocument, toAppearance, uploadFrozenCopy, uploadQueryString, useDocumentMarkup, useDocumentSignatures, useDocumentTools, useIsOnline, useOptionalDocumentTools, useSignDocument, useSignatureVerification, versionsWithMarkup };
836
861
  //# sourceMappingURL=index.js.map
837
862
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/document-tools/environment.tsx","../../src/document-tools/document-pdf.ts","../../src/document-tools/production.ts","../../src/document-tools/markup-store.ts","../../src/document-tools/markup-transfer.ts","../../src/document-tools/markup-download.ts","../../src/document-tools/useDocumentMarkup.ts","../../src/document-tools/frozen-copy.ts","../../src/document-tools/can-annotate.ts","../../src/document-tools/useIsOnline.ts","../../src/document-tools/signing.ts","../../src/document-tools/verification.ts"],"names":["useMemo","useQuery"],"mappings":";;;;;;;;;;;;;;;AA+DO,SAAS,kBAAkB,KAAA,EAAoC;AACpE,EAAA,MAAM,MAAA,GAAS,IAAI,eAAA,EAAgB;AACnC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAChD,IAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW;AAC3C,IAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,CAAM,OAAA,CAAQ,KAAK,IAAI,KAAA,GAAQ,CAAC,KAAK,CAAA,EAAG,MAAA,CAAO,MAAA,CAAO,GAAA,EAAK,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,EAC5F;AACA,EAAA,OAAO,OAAO,QAAA,EAAS;AACzB;AA+CO,SAAS,YAAA,CAAa,MAAY,QAAA,EAAwB;AAC/D,EAAA,MAAM,GAAA,GAAM,GAAA,CAAI,eAAA,CAAgB,IAAI,CAAA;AACpC,EAAA,MAAM,CAAA,GAAI,QAAA,CAAS,aAAA,CAAc,GAAG,CAAA;AACpC,EAAA,CAAA,CAAE,IAAA,GAAO,GAAA;AACT,EAAA,CAAA,CAAE,QAAA,GAAW,QAAA;AACb,EAAA,QAAA,CAAS,IAAA,CAAK,YAAY,CAAC,CAAA;AAC3B,EAAA,CAAA,CAAE,KAAA,EAAM;AACR,EAAA,CAAA,CAAE,MAAA,EAAO;AACT,EAAA,UAAA,CAAW,MAAM,GAAA,CAAI,eAAA,CAAgB,GAAG,GAAG,GAAI,CAAA;AACjD;AAGO,SAAS,aAAa,MAAA,EAA6B;AACxD,EAAA,OAAO,OAAO,EAAE,IAAA,EAAM,KAAA,EAAM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,IAAA,EAAM,EAAE,SAAA,EAAU,EAAE,EAAG,CAAA;AAAA,IAClE,OAAA,EAAS,MAAM,0BAAA,CAA2B,MAAA,EAAQ,SAAU,CAAA;AAAA,IAC5D,OAAA,EAAS,CAAC,CAAC,SAAA;AAAA,IACX,KAAA,EAAO;AAAA,GACR,CAAA;AACH;AAUA,eAAsB,eAAA,CACpB,MACA,YAAA,EACoB;AACpB,EAAA,MAAM,IAAA,GAAO,MAAM,SAAA,CAAU,IAAI,CAAA;AACjC,EAAA,IAAI,IAAA,KAAS,aAAa,eAAA,CAAgB,WAAA,IAAe,OAAO,EAAE,MAAM,SAAA,EAAU;AAClF,EAAA,MAAM,SAAA,GAAY,YAAA,CAAa,UAAA,CAAW,IAAA,CAAK,CAAC,MAAM,CAAA,CAAE,MAAA,CAAO,WAAA,EAAY,KAAM,IAAI,CAAA;AACrF,EAAA,OAAO,SAAA,GAAY,EAAE,IAAA,EAAM,SAAA,EAAW,WAAU,GAAI,EAAE,MAAM,MAAA,EAAO;AACrE","file":"index.js","sourcesContent":["/**\n * The host app's side of the document tools (markup, freeze, e-signing, versions): the one place\n * the tools reach the app. They never import a store, a router, a toast library or app API code;\n * the host passes what it has to `<DocumentToolsProvider>` and every optional field has a default.\n *\n * `client` is an openapi-fetch client for the ARBI API (`ArbiClient['fetch']` from\n * `@arbidocs/client`, or `arbi.getClient().fetch` from an `@arbidocs/sdk` `Arbi`), signed in with the\n * user's session; it carries the auth.\n */\n\nimport { createContext, useContext, useMemo, type ReactNode } from 'react'\nimport type { ArbiClient, operations } from '@arbidocs/client'\nimport { useDeploymentDomain } from '../useArbi'\n\nexport type DocumentToolsClient = ArbiClient['fetch']\n\nexport type DocumentToolsNoticeKind = 'success' | 'error' | 'info' | 'warning'\n\nexport interface DocumentToolsNoticeOptions {\n /** A second line under the message. */\n description?: string\n /** One action button on the notice (\"Email it\"). */\n action?: { label: string; onClick: () => void }\n}\n\nexport type DocumentToolsNotify = (\n message: string,\n kind: DocumentToolsNoticeKind,\n options?: DocumentToolsNoticeOptions\n) => void\n\nexport interface DocumentToolsUser {\n /** The name marks are authored as and the signer's name is prefilled with. */\n name: string\n /** The sign-in email: signing re-derives the user's key from it and the password. */\n email?: string | null\n}\n\n/** What changed about a document, so the host can refresh its own lists and caches. */\nexport type DocumentChange =\n /** A version's markup got its first mark or lost its last one. */\n | 'markup'\n /** A signature was added: the document has a new current version. */\n | 'signed'\n /** A new document was made from it (a frozen copy). The ids are the NEW documents. */\n | 'copy'\n\n/**\n * The `/v1/document/upload` query, typed from the API schema: `derived_from` is a list (a\n * production set is derived from every document in it), `shared` a boolean.\n */\nexport type DocumentUploadQuery = NonNullable<operations['upload_documents']['parameters']['query']>\n\nexport interface DocumentUploadRequest {\n file: File\n /** `/v1/document/upload` query: `derived_from`, `derived_role`, `shared`, `folder`. */\n query: DocumentUploadQuery\n}\n\n/**\n * The upload query as a URL query string, for a host that posts the upload itself (an XHR with\n * progress): a list repeats its key (`derived_from=a&derived_from=b`), empty values are left out.\n */\nexport function uploadQueryString(query: DocumentUploadQuery): string {\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (value === null || value === undefined) continue\n for (const item of Array.isArray(value) ? value : [value]) params.append(key, String(item))\n }\n return params.toString()\n}\n\nexport interface DocumentToolsEnvironment {\n client: DocumentToolsClient\n /**\n * The deployment domain the user's keys are derived for. Needed for signing. Default: the one\n * the enclosing `<ArbiProvider>`'s `Arbi` computes (`arbi.getDeploymentDomain()`), if any.\n */\n deploymentDomain?: string\n /** The signed-in user; marks are authored as \"You\" without one, and signing is unavailable. */\n user?: DocumentToolsUser | null\n /** Surface a transient message. Default: none (errors still show inline where they can). */\n notify?: DocumentToolsNotify\n /** Open a document or a version reference (`doc-…@v2`): the copy just made, the signed copy. */\n openDocument?: (documentRef: string) => void\n /**\n * Documents changed on the server (see {@link DocumentChange}); refresh the host's lists. The\n * tools wait for it before opening the document, so a copy is listed when it opens.\n */\n onDocumentsChanged?: (documentIds: string[], change: DocumentChange) => void | Promise<void>\n /** Upload a derived copy. Default: `POST /v1/document/upload` through `client`. */\n uploadDocument?: (\n request: DocumentUploadRequest\n ) => Promise<{ doc_ext_ids?: string[] } | undefined>\n /** Save a file to the user's computer. Default: a temporary download link. */\n saveFile?: (blob: Blob, fileName: string) => void\n /** Email a document (offered once it is signed). Omitted: no \"Email it\". */\n emailDocument?: (documentRef: string) => void\n /**\n * The public page that checks a signature (the certificate) in this app. When given, \"View\n * certificate\" opens it in preference to the backend's `certificate_url` (which is on the\n * deployment domain, like the link embedded in the signed PDF). Without it: the backend's\n * `certificate_url`, else `/verify/{reference}` on this origin.\n */\n certificateUrl?: (reference: string) => string\n}\n\n/** The environment with every default filled in. */\nexport interface ResolvedDocumentToolsEnvironment extends DocumentToolsEnvironment {\n notify: DocumentToolsNotify\n saveFile: (blob: Blob, fileName: string) => void\n uploadDocument: (\n request: DocumentUploadRequest\n ) => Promise<{ doc_ext_ids?: string[] } | undefined>\n}\n\n/** Save a blob through a temporary `<a download>`. */\nexport function downloadBlob(blob: Blob, fileName: string): void {\n const url = URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.href = url\n a.download = fileName\n document.body.appendChild(a)\n a.click()\n a.remove()\n setTimeout(() => URL.revokeObjectURL(url), 1000)\n}\n\n/** The default upload: multipart `files` to `/v1/document/upload` through the API client. */\nexport function clientUpload(client: DocumentToolsClient) {\n return async ({ file, query }: DocumentUploadRequest) => {\n const formData = new FormData()\n formData.append('files', file)\n const { data, response } = await client.POST('/v1/document/upload', {\n params: { query },\n // The schema types the multipart body as `{ files: string[] }`; the FormData is sent as is.\n body: formData as unknown as { files: string[] },\n bodySerializer: () => formData,\n })\n if (!response.ok) throw new Error(`Upload failed with status ${response.status}`)\n return data\n }\n}\n\nexport function defaultCertificateUrl(reference: string): string {\n const origin = typeof location === 'undefined' ? '' : location.origin\n return `${origin}/verify/${encodeURIComponent(reference)}`\n}\n\n/**\n * Where \"View certificate\" goes for a signature: the host's `certificateUrl(reference)` when it\n * gives one, else the `certificate_url` the backend returned, else `/verify/{reference}` here.\n */\nexport function certificateLink(\n signature: { reference: string; certificate_url?: string | null },\n certificateUrl?: (reference: string) => string\n): string {\n if (certificateUrl) return certificateUrl(signature.reference)\n return signature.certificate_url || defaultCertificateUrl(signature.reference)\n}\n\nconst DocumentToolsContext = createContext<ResolvedDocumentToolsEnvironment | null>(null)\n\nexport interface DocumentToolsProviderProps extends DocumentToolsEnvironment {\n children: ReactNode\n}\n\nexport function DocumentToolsProvider({ children, ...env }: DocumentToolsProviderProps) {\n const arbiDeploymentDomain = useDeploymentDomain()\n const {\n client,\n deploymentDomain,\n user,\n notify,\n openDocument,\n onDocumentsChanged,\n uploadDocument,\n saveFile,\n emailDocument,\n certificateUrl,\n } = env\n const value = useMemo<ResolvedDocumentToolsEnvironment>(\n () => ({\n client,\n deploymentDomain: deploymentDomain ?? arbiDeploymentDomain,\n user,\n openDocument,\n onDocumentsChanged,\n emailDocument,\n notify: notify ?? (() => {}),\n saveFile: saveFile ?? downloadBlob,\n uploadDocument: uploadDocument ?? clientUpload(client),\n certificateUrl,\n }),\n [\n client,\n deploymentDomain,\n arbiDeploymentDomain,\n user,\n notify,\n openDocument,\n onDocumentsChanged,\n uploadDocument,\n saveFile,\n emailDocument,\n certificateUrl,\n ]\n )\n return <DocumentToolsContext.Provider value={value}>{children}</DocumentToolsContext.Provider>\n}\n\n/** The host's environment, or `null` outside a `<DocumentToolsProvider>`. */\nexport function useOptionalDocumentTools(): ResolvedDocumentToolsEnvironment | null {\n return useContext(DocumentToolsContext)\n}\n\n/** The host's environment; throws outside a `<DocumentToolsProvider>`. */\nexport function useDocumentTools(): ResolvedDocumentToolsEnvironment {\n const env = useContext(DocumentToolsContext)\n if (!env) throw new Error('The document tools must be used within a <DocumentToolsProvider>')\n return env\n}\n","/**\n * A document's bytes, through the host's API client: the PDF the viewer and the tools draw on\n * (`/view`: the file itself for a PDF, its PDF rendering for a Word or text file) and the stored\n * file (`/download`). Either takes a document id or a version reference `doc-…@v{n}`.\n */\n\nimport { parseVersionRef } from '../artifacts/versions'\nimport type { DocumentToolsClient } from './environment'\n\nexport interface DocumentFetchOptions {\n /** The version to fetch. Default: the one `documentRef` names, else the current version. */\n version?: number | null\n signal?: AbortSignal\n}\n\n/** A document's bytes could not be fetched; `status` is the HTTP status. */\nexport class DocumentFetchError extends Error {\n readonly status: number\n constructor(message: string, status: number) {\n super(message)\n this.name = 'DocumentFetchError'\n this.status = status\n }\n}\n\nasync function fetchDocumentBytes(\n client: DocumentToolsClient,\n endpoint: '/v1/document/{document_ext_id}/view' | '/v1/document/{document_ext_id}/download',\n documentRef: string,\n options: DocumentFetchOptions,\n headers: Record<string, string>,\n what: string\n): Promise<Blob> {\n const ref = parseVersionRef(documentRef)\n const version = options.version ?? ref.version\n const { data, response } = await client.GET(endpoint, {\n params: { path: { document_ext_id: ref.docId }, query: version ? { version } : {} },\n headers,\n parseAs: 'blob',\n signal: options.signal,\n })\n if (!response.ok || !(data instanceof Blob)) {\n throw new DocumentFetchError(\n `${what} could not be loaded (${response.status})`,\n response.status\n )\n }\n return data\n}\n\n/**\n * The PDF of a document version: `GET /v1/document/{id}/view?version=` with\n * `Accept: application/pdf`. Throws a {@link DocumentFetchError} when there is none (yet).\n */\nexport function fetchDocumentPdf(\n client: DocumentToolsClient,\n documentRef: string,\n options: DocumentFetchOptions = {}\n): Promise<Blob> {\n return fetchDocumentBytes(\n client,\n '/v1/document/{document_ext_id}/view',\n documentRef,\n options,\n { Accept: 'application/pdf' },\n 'The PDF'\n )\n}\n\n/** The stored file of a document version, as uploaded: `GET /v1/document/{id}/download`. */\nexport function fetchDocumentFile(\n client: DocumentToolsClient,\n documentRef: string,\n options: DocumentFetchOptions = {}\n): Promise<Blob> {\n return fetchDocumentBytes(\n client,\n '/v1/document/{document_ext_id}/download',\n documentRef,\n options,\n {},\n 'The file'\n )\n}\n","/**\n * Production sets: number the selected documents with Bates labels (optionally a QR code back to\n * each document and an index page) and save the result back to the workspace. The dialog is\n * `ProductionSetDialog` in `@arbidocs/blocks/document-tools`; this is its data side.\n *\n * A PDF is numbered as stored (`/download`). Any other document is numbered through its PDF\n * rendition (`/view`, what the viewer shows for a Word or text file); one without a rendition is\n * left out. Saved results are new documents derived from their sources (role `production`) in a\n * Productions folder, shared with the workspace only if every source is. The originals never\n * change.\n *\n * pdf-lib (the numbering) is loaded only when a production is built, so importing this module\n * stays as light as the rest of the document tools.\n */\n\nimport type { components } from '@arbidocs/client'\nimport type { ProductionChoices } from '../annotations/ProductionDialog'\nimport type { BundleFile, BundleIndexEntry, BundleItem } from '../annotations/freeze/bundle'\nimport { DocumentFetchError, fetchDocumentFile, fetchDocumentPdf } from './document-pdf'\nimport type {\n DocumentToolsClient,\n DocumentToolsEnvironment,\n DocumentUploadQuery,\n} from './environment'\n\n/** The fields of a document record (`DocResponse`) a production uses. */\nexport type ProductionSource = Pick<\n components['schemas']['DocResponse'],\n 'external_id' | 'file_name' | 'file_type' | 'shared'\n> & { doc_metadata?: { title?: string | null } | null }\n\nexport const PRODUCTIONS_FOLDER = 'Productions'\n\nconst extensionOf = (fileName: string | null | undefined) => {\n const name = (fileName ?? '').toLowerCase()\n const dot = name.lastIndexOf('.')\n return dot < 0 ? '' : name.slice(dot + 1)\n}\n\n/** Media, archives and design files: no PDF version to number. */\nconst NO_RENDITION_EXTENSIONS = new Set(\n [\n // images\n 'jpg jpeg png gif bmp tiff tif webp heic',\n // video and audio\n 'mp4 mpeg mpg webm mov avi mkv mp3 wav m4a aac ogg flac',\n // archives, binaries, design files\n 'zip rar 7z tar gz exe bin dmg iso apk msi dll so psd ai sketch',\n ]\n .join(' ')\n .split(' ')\n)\n\nexport const isPdfDocument = (doc: ProductionSource) =>\n /pdf/i.test(doc.file_type ?? '') || extensionOf(doc.file_name) === 'pdf'\n\n/** True for a document with no PDF version to number (media, archives and the like). */\nexport const hasNoRendition = (doc: ProductionSource) =>\n !isPdfDocument(doc) && NO_RENDITION_EXTENSIONS.has(extensionOf(doc.file_name))\n\n/** The name a document goes by in the dialog and the index: its title, else its file name. */\nexport const productionDocumentName = (doc: ProductionSource) =>\n doc.doc_metadata?.title || doc.file_name || doc.external_id\n\nconst isPdfBytes = (bytes: Uint8Array) =>\n bytes.length > 4 && String.fromCharCode(...bytes.subarray(0, 5)) === '%PDF-'\n\n/**\n * The PDF to number for `doc`: the file itself, or the PDF version of anything else. `null` when a\n * non-PDF has no PDF version (yet), so it is left out; a PDF that cannot be downloaded throws.\n */\nexport async function fetchProductionPdf(\n client: DocumentToolsClient,\n doc: ProductionSource\n): Promise<Uint8Array | null> {\n const pdf = isPdfDocument(doc)\n let blob: Blob\n try {\n blob = await (pdf ? fetchDocumentFile : fetchDocumentPdf)(client, doc.external_id)\n } catch (e) {\n if (!pdf && e instanceof DocumentFetchError) return null\n throw e\n }\n const bytes = new Uint8Array(await blob.arrayBuffer())\n return pdf || isPdfBytes(bytes) ? bytes : null\n}\n\nconst safeName = (name: string) => name.replace(/[\\\\/:*?\"<>|]+/g, '_').trim()\n\n/** \"Production ACME-000001-ACME-000042\": names the files and folder of one production. */\nexport function productionTitle(firstLabel: string, lastLabel: string): string {\n return safeName(`Production ${firstLabel}-${lastLabel}`)\n}\n\n/** Where a production is saved: the Productions folder, or a folder of its own per document. */\nexport function productionFolder(title: string, merged: boolean): string {\n return merged ? PRODUCTIONS_FOLDER : `${PRODUCTIONS_FOLDER}/${title}`\n}\n\n/** In the workspace a per-document file says which range it holds, beside its original. */\nexport function productionFileName(file: BundleFile, title: string): string {\n if (!file.firstLabel) return `${title} index.pdf`\n return `${file.name.replace(/\\.pdf$/i, '')} (${file.firstLabel}-${file.lastLabel}).pdf`\n}\n\nconst csvCell = (value: string | number) => `\"${String(value).replace(/\"/g, '\"\"')}\"`\n\n/** The `index.csv` of a per-document production: every document with its file and range. */\nexport function productionIndexCsv(index: readonly BundleIndexEntry[]): string {\n const rows = index.map((e) =>\n [e.documentId, e.name, e.file, e.pages, e.firstLabel, e.lastLabel].map(csvCell).join(',')\n )\n return ['document_id,name,file,pages,first_label,last_label', ...rows].join('\\n')\n}\n\nexport interface ProductionUpload {\n name: string\n bytes: Uint8Array\n /** The documents this file was made from. */\n sources: ProductionSource[]\n}\n\n/** Save each file as a new workspace document derived from its sources; returns the new ids. */\nexport async function saveProductionFiles(\n upload: NonNullable<DocumentToolsEnvironment['uploadDocument']>,\n files: readonly ProductionUpload[],\n folder: string\n): Promise<string[]> {\n const ids: string[] = []\n for (const file of files) {\n const query: DocumentUploadQuery = {\n derived_from: file.sources.map((doc) => doc.external_id),\n derived_role: 'production',\n shared: file.sources.every((doc) => doc.shared),\n folder,\n }\n const response = await upload({\n file: new File([file.bytes as BlobPart], file.name, { type: 'application/pdf' }),\n query,\n })\n ids.push(...(response?.doc_ext_ids ?? []))\n }\n return ids\n}\n\nexport interface BuildProductionOptions {\n /** The link a document's QR code opens (the document in the host app). */\n documentUrl: (documentId: string) => string\n /** Who produced the set; recorded in a merged file's metadata. */\n author?: string\n onProgress?: (done: number, total: number) => void\n}\n\nexport interface BuiltProduction {\n title: string\n merged: boolean\n /** The numbered files: one merged PDF (named after its range), or one per document (+ index). */\n files: BundleFile[]\n index: BundleIndexEntry[]\n /** The documents numbered, in order. */\n included: ProductionSource[]\n /** Documents left out because they have no PDF version yet. */\n noRendition: ProductionSource[]\n /** The files as they are saved to the workspace, each with the documents it was made from. */\n uploads: ProductionUpload[]\n folder: string\n}\n\n/**\n * Fetch each document's PDF (in `choices.order`) and number the set. Throws when none of the\n * documents has a PDF version, or when a PDF cannot be fetched.\n */\nexport async function buildProduction(\n client: DocumentToolsClient,\n documents: readonly ProductionSource[],\n choices: ProductionChoices,\n options: BuildProductionOptions\n): Promise<BuiltProduction> {\n const byId = new Map(documents.map((doc) => [doc.external_id, doc]))\n const included: ProductionSource[] = []\n const noRendition: ProductionSource[] = []\n const items: BundleItem[] = []\n for (const doc of choices.order.flatMap((id) => byId.get(id) ?? [])) {\n const bytes = await fetchProductionPdf(client, doc)\n if (!bytes) {\n noRendition.push(doc)\n continue\n }\n included.push(doc)\n items.push({\n name: productionDocumentName(doc),\n documentId: doc.external_id,\n bytes,\n qrUrl: options.documentUrl(doc.external_id),\n })\n }\n if (items.length === 0) {\n throw new Error('None of these documents has a PDF version to number yet.')\n }\n\n const { buildBundle } = await import('../annotations/freeze/bundle')\n const result = await buildBundle(items, {\n layout: choices.layout,\n bates: {\n prefix: choices.prefix,\n start: choices.start,\n digits: choices.digits,\n corner: choices.corner,\n },\n qr: choices.qr,\n // The QR code sits in the bottom corner the label is not in.\n qrCorner: choices.corner.endsWith('left') ? 'bottom-right' : 'bottom-left',\n indexPage: choices.indexPage,\n author: options.author,\n onProgress: options.onProgress,\n })\n\n const title = productionTitle(\n result.index[0].firstLabel,\n result.index[result.index.length - 1].lastLabel\n )\n const merged = choices.layout === 'merged'\n // A merged file is named after its range; per-document files keep their document names.\n const files = merged ? [{ ...result.files[0], name: `${title}.pdf` }] : result.files\n const sourceOf = new Map(result.index.map((e) => [e.file, byId.get(e.documentId)!]))\n const uploads = files.map((file) => ({\n name: merged ? file.name : productionFileName(file, title),\n bytes: file.bytes,\n // The merged file (and a separate index) is made from every document; each per-document\n // file from its own.\n sources: merged || !sourceOf.has(file.name) ? included : [sourceOf.get(file.name)!],\n }))\n return {\n title,\n merged,\n files,\n index: result.index,\n included,\n noRendition,\n uploads,\n folder: productionFolder(title, merged),\n }\n}\n","/**\n * The annotation store for a document version's MARKUP on the server: `GET`/`PUT\n * /v1/document/{id}/markup`. The server keeps the marks as native PDF annotations in an encrypted\n * `{doc}-markup.pdf` next to the version (same document id, the document's own privacy); this store\n * only moves the layer and its revision.\n *\n * Optimistic concurrency: every save names the revision it started from. When someone else saved\n * first the server answers 409; the store then re-reads the latest layer, merges it with ours by\n * annotation id (`mergeLayers`: union, last edit wins per mark, replies unioned, our deletions\n * stay deleted) and saves again. The merged layer is returned so the viewer shows their marks too.\n *\n * Deletions are tracked as tombstones for the session: an id this session has seen that is no\n * longer in the layer it saves was deleted here, and a concurrent edit elsewhere cannot bring it\n * back.\n */\n\nimport {\n AnnotationStoreOfflineError,\n LAYER_SCHEMA_VERSION,\n mergeLayers,\n parseLayer,\n type AnnotationLayer,\n type AnnotationStore,\n} from '../annotations'\nimport type { DocumentToolsClient } from './environment'\n\n/** How many times a save re-reads and merges after a 409 before giving up (each is a real race). */\nexport const MAX_MERGE_ATTEMPTS = 5\n/** Below this many bytes a save uses `keepalive`, so it completes even if the page unloads. */\nconst KEEPALIVE_LIMIT = 60_000\n\nexport interface MarkupSnapshot {\n revision: number\n count: number\n canEdit: boolean\n}\n\nexport interface MarkupStoreOptions {\n /** The version the markup belongs to; omitted = the document's current version. */\n version?: number\n /** The ARBI API client (see `DocumentToolsEnvironment.client`). */\n client: DocumentToolsClient\n /** After every successful save: the new revision and how many marks the markup holds. */\n onSaved?: (snapshot: MarkupSnapshot) => void\n}\n\nexport interface MarkupStore extends AnnotationStore {\n snapshot(): MarkupSnapshot\n}\n\ninterface ServerLayer {\n revision: number\n layer: AnnotationLayer\n canEdit: boolean\n}\n\nexport class MarkupStoreError extends Error {\n constructor(\n message: string,\n readonly status?: number\n ) {\n super(message)\n this.name = 'MarkupStoreError'\n }\n}\n\nconst detailOf = (error: unknown, fallback: string) => {\n const detail = (error as { detail?: unknown } | undefined)?.detail\n return typeof detail === 'string' ? detail : fallback\n}\n\n/** A request that never reached the server (no network, DNS, CORS) is \"offline\", not a failure. */\nasync function call<T>(request: () => Promise<T>): Promise<T> {\n try {\n return await request()\n } catch (e) {\n if (e instanceof TypeError || (typeof navigator !== 'undefined' && !navigator.onLine)) {\n throw new AnnotationStoreOfflineError()\n }\n throw e\n }\n}\n\nexport function createMarkupStore({ version, client, onSaved }: MarkupStoreOptions): MarkupStore {\n let revision = 0\n let count = 0\n let canEdit = false\n /** The layer as last read from or written to the server: the base of a merge. */\n let base: AnnotationLayer | null = null\n /** Every mark id this session has held: one missing from a save was deleted here. */\n const seen = new Set<string>()\n const remember = (layer: AnnotationLayer) => {\n for (const a of layer.annotations) seen.add(a.id)\n }\n const query = version ? { version } : {}\n\n async function read(documentId: string, ifNoneMatch?: number): Promise<ServerLayer | null> {\n const { data, error, response } = await call(() =>\n client.GET('/v1/document/{document_ext_id}/markup', {\n params: { path: { document_ext_id: documentId }, query },\n headers: ifNoneMatch === undefined ? undefined : { 'If-None-Match': `\"${ifNoneMatch}\"` },\n })\n )\n if (response.status === 304) return null\n if (error || !data) {\n throw new MarkupStoreError(\n detailOf(error, `The markup could not be loaded (${response.status})`),\n response.status\n )\n }\n const layer = parseLayer({\n schema: LAYER_SCHEMA_VERSION,\n documentId,\n annotations: data.annotations ?? [],\n updatedAt: data.updated_at ?? new Date().toISOString(),\n })\n return { revision: data.revision ?? 0, layer, canEdit: !!data.can_edit }\n }\n\n function adopt(server: ServerLayer) {\n revision = server.revision\n canEdit = server.canEdit\n base = server.layer\n count = server.layer.annotations.length\n remember(server.layer)\n }\n\n async function put(layer: AnnotationLayer, from: number) {\n return call(() =>\n client.PUT('/v1/document/{document_ext_id}/markup', {\n params: { path: { document_ext_id: layer.documentId }, query },\n headers: { 'If-Match': `\"${from}\"` },\n body: { annotations: layer.annotations as never, base_revision: from },\n // A save started as the page closes must outlive it; browsers cap such bodies at 64 KB.\n keepalive: JSON.stringify(layer.annotations).length < KEEPALIVE_LIMIT,\n })\n )\n }\n\n return {\n snapshot: () => ({ revision, count, canEdit }),\n canEdit: () => canEdit,\n\n async load(documentId) {\n const server = await read(documentId)\n if (!server) throw new MarkupStoreError('The markup could not be loaded')\n adopt(server)\n return server.layer\n },\n\n async save(layer) {\n remember(layer)\n let mine = layer\n for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {\n const { data, error, response } = await put(mine, revision)\n if (response.ok && data) {\n revision = data.revision\n count = data.count\n base = mine\n remember(mine)\n onSaved?.({ revision, count, canEdit })\n return mine\n }\n if (response.status === 409) {\n // Someone saved first: their layer, merged with ours, is what we save next.\n const latest = await read(layer.documentId)\n if (!latest) throw new MarkupStoreError('The markup could not be re-read')\n const deleted = new Set(\n [...seen].filter((id) => !mine.annotations.some((a) => a.id === id))\n )\n const merged = mergeLayers({ base, mine, theirs: latest.layer, deleted })\n revision = latest.revision\n canEdit = latest.canEdit\n base = latest.layer\n remember(latest.layer)\n mine = merged\n continue\n }\n if (response.status === 403) canEdit = false\n throw new MarkupStoreError(\n detailOf(error, `The markup could not be saved (${response.status})`),\n response.status\n )\n }\n throw new MarkupStoreError('The markup keeps changing; it will be saved on the next edit')\n },\n\n async pull(documentId) {\n const server = await read(documentId, revision)\n if (!server || server.revision === revision) return null\n adopt(server)\n return server.layer\n },\n }\n}\n","/**\n * Moving marks INTO a version's markup without the viewer: the one-time migration of layers kept in\n * this browser before markup lived on the server, and \"copy open comments\" from an older version's\n * markup onto the current one (a new version — signed, synced from Drive, saved from Word — starts\n * with an empty markup; redactions never carry over).\n *\n * Both are unions by annotation id, so running them twice adds nothing twice.\n */\n\nimport {\n LAYER_SCHEMA_VERSION,\n emptyLayer,\n mergeLayers,\n parseLayer,\n type Annotation,\n type AnnotationLayer,\n} from '../annotations'\nimport type { DocumentToolsClient } from './environment'\nimport { createMarkupStore } from './markup-store'\n\nexport const LEGACY_LAYER_PREFIX = 'arbi:annotations:'\n\nexport interface VersionInfo {\n n: number\n created_at?: string | null\n markup_count?: number | null\n}\n\nfunction storage(): Storage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\n/** The layer this browser kept for a document before markup moved to the server, if any. */\nexport function readLegacyLayer(documentId: string): AnnotationLayer | null {\n try {\n const raw = storage()?.getItem(LEGACY_LAYER_PREFIX + documentId)\n if (!raw) return null\n return parseLayer(JSON.parse(raw))\n } catch {\n return null // unreadable: nothing worth migrating\n }\n}\n\nexport function forgetLegacyLayer(documentId: string): void {\n try {\n storage()?.removeItem(LEGACY_LAYER_PREFIX + documentId)\n } catch {\n // storage blocked: nothing to forget\n }\n}\n\n/**\n * Which version each legacy mark belongs to: the version that was current when it was made. A\n * document's id is the id of its first version (older layers were made on it); a layer made after\n * the versions moved inside the document was made on whatever version was then current.\n */\nexport function marksByVersion(\n layer: AnnotationLayer,\n versions: VersionInfo[]\n): Map<number, Annotation[]> {\n const sorted = [...versions].sort((a, b) => a.n - b.n)\n const out = new Map<number, Annotation[]>()\n for (const mark of layer.annotations) {\n const at = Date.parse(mark.createdAt)\n let target = sorted[0]?.n ?? 1\n for (const v of sorted) {\n const created = v.created_at ? Date.parse(v.created_at) : Number.NaN\n if (!Number.isNaN(created) && !Number.isNaN(at) && created <= at) target = v.n\n }\n out.set(target, [...(out.get(target) ?? []), mark])\n }\n return out\n}\n\n/** Add marks to one version's markup (union by id); returns how many were new. */\nexport async function addToMarkup(\n documentId: string,\n version: number | undefined,\n marks: Annotation[],\n client: DocumentToolsClient\n): Promise<number> {\n const store = createMarkupStore({ version, client })\n const current = await store.load(documentId)\n const incoming: AnnotationLayer = {\n ...emptyLayer(documentId, new Date().toISOString()),\n annotations: marks,\n }\n // Theirs (the server) wins any tie: a mark already in the markup is never overwritten by an\n // older browser copy of it.\n const merged = mergeLayers({ base: null, mine: current, theirs: incoming })\n const added = merged.annotations.length - current.annotations.length\n if (added > 0) await store.save(parseLayer({ ...merged, schema: LAYER_SCHEMA_VERSION }))\n return added\n}\n\n/**\n * Migrate this browser's layer for a document into its markup, version by version, then forget\n * the browser copy. Throws (and keeps the browser copy) if any version could not be saved.\n */\nexport async function migrateLegacyLayer(\n documentId: string,\n layer: AnnotationLayer,\n versions: VersionInfo[],\n currentVersion: number,\n client: DocumentToolsClient\n): Promise<number> {\n let added = 0\n for (const [n, marks] of marksByVersion(layer, versions.length ? versions : [{ n: 1 }])) {\n added += await addToMarkup(documentId, n === currentVersion ? undefined : n, marks, client)\n }\n forgetLegacyLayer(documentId)\n return added\n}\n\n/** The unresolved comment threads (with replies) of a version's markup. */\nexport async function openThreadsOf(\n documentId: string,\n version: number,\n client: DocumentToolsClient\n): Promise<Annotation[]> {\n const layer = await createMarkupStore({ version, client }).load(documentId)\n return layer.annotations.filter((a) => a.kind === 'comment' && !a.resolved)\n}\n\n/** Copy the open comment threads of an older version onto the current version's markup. */\nexport async function copyOpenThreads(\n documentId: string,\n fromVersion: number,\n client: DocumentToolsClient\n): Promise<number> {\n const threads = await openThreadsOf(documentId, fromVersion, client)\n if (!threads.length) return 0\n return addToMarkup(documentId, undefined, threads, client)\n}\n\n/** Version entries of a document as the API returns them (`DocResponse.versions`). */\nexport function versionsWithMarkup(versions: VersionInfo[] | null | undefined): VersionInfo[] {\n return (versions ?? []).filter((v) => (v.markup_count ?? 0) > 0)\n}\n","/**\n * \"Download with markup\": a document version's markup PDF, the PDF with its annotations as native\n * PDF annotations (comments, highlights, stamps, unapplied redactions), which Acrobat and Preview\n * show. The plain Download serves the original. Kept apart from the annotation layer code so a\n * documents list can offer it without loading the annotation tools.\n *\n * A SIGNED version is locked: nothing but a further signature changes it. Its markup stays in the\n * separate markup layer (a title beside the signature, say) and is never written into its PDF, so\n * it has no \"Download with markup\"; the plain Download is the signed file as it is.\n */\n\nimport type { DocumentToolsClient } from './environment'\n\ninterface DocumentVersions {\n current_version?: number | null\n versions?: Array<{ n: number; markup_count?: number | null; reason?: string | null }> | null\n}\n\n/** Why \"Download with markup\" is off for a signed version. */\nexport const SIGNED_LOCKED_REASON =\n \"Signed documents can't be changed — download the signed file instead\"\n\n/** Whether a version (default: the current one) is a signed copy, per its version entry. */\nexport function isSignedVersion(doc: DocumentVersions, version?: number): boolean {\n const n = version ?? doc.current_version ?? 1\n return (doc.versions ?? []).some((v) => v.n === n && v.reason === 'signed')\n}\n\nexport class MarkupDownloadError extends Error {\n constructor(\n message: string,\n readonly status?: number\n ) {\n super(message)\n this.name = 'MarkupDownloadError'\n }\n}\n\n/** Whether a document's current version has markup (per its version entries). */\nexport function currentHasMarkup(doc: DocumentVersions): boolean {\n const n = doc.current_version ?? 1\n return (doc.versions ?? []).some((v) => v.n === n && (v.markup_count ?? 0) > 0)\n}\n\n/** Fetch a version's markup PDF (default: the current version's). */\nexport async function fetchMarkupPdf(\n client: DocumentToolsClient,\n documentId: string,\n version?: number\n): Promise<{ blob: Blob; fileName: string }> {\n const { data, response } = await client.GET('/v1/document/{document_ext_id}/markup/pdf', {\n params: { path: { document_ext_id: documentId }, query: version ? { version } : {} },\n parseAs: 'blob',\n })\n if (!response.ok || !data) {\n throw new MarkupDownloadError(\n response.status === 404\n ? 'This document has no markup yet'\n : // The server refuses a signed version: its PDF takes no more changes.\n response.status === 409\n ? SIGNED_LOCKED_REASON\n : 'The markup could not be downloaded',\n response.status\n )\n }\n const disposition = response.headers.get('content-disposition') ?? ''\n const utf8 = /filename\\*=UTF-8''([^;]+)/i.exec(disposition)?.[1]\n const plain = /filename=\"([^\"]+)\"/i.exec(disposition)?.[1]\n const fileName = utf8 ? decodeURIComponent(utf8) : (plain ?? 'markup.pdf')\n return { blob: data as Blob, fileName }\n}\n","/**\n * Markup state for the document page: whether the version on screen has markup (so the viewer\n * opens on it, the default view), the \"Show original\" toggle, \"Download with markup\", the one-time\n * migration of this browser's old annotation layer, and the note shown when the markup is on an\n * older version (with \"copy open comments\").\n *\n * Whether a version has markup comes from the document's version entries (`markup_count`), kept\n * current by the viewer's own saves (`onMarkupChange`) until the document is refetched.\n */\n\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useDocumentTools } from './environment'\nimport type { MarkupSnapshot } from './markup-store'\nimport { SIGNED_LOCKED_REASON, fetchMarkupPdf } from './markup-download'\nimport {\n copyOpenThreads,\n forgetLegacyLayer,\n migrateLegacyLayer,\n readLegacyLayer,\n versionsWithMarkup,\n type VersionInfo,\n} from './markup-transfer'\n\nexport const SIGNED_UNCHANGED =\n 'The signed PDF is unchanged: the comments are kept beside it as markup.'\n\nexport interface MarkupDocument {\n external_id: string\n shared?: boolean | null\n current_version?: number | null\n versions?: VersionInfo[] | null\n}\n\nexport interface LegacyPrompt {\n count: number\n busy: boolean\n add: () => void\n discard: () => void\n}\n\nexport interface OlderMarkupNote {\n version: number\n busy: boolean\n /** The current version is a signed copy: say that copying leaves its signed PDF as it is. */\n signed: boolean\n copy: () => void\n}\n\nexport function useDocumentMarkup(\n documentData: MarkupDocument | null | undefined,\n /** The version on screen when it is an older one (a read-only snapshot). */\n snapshotVersion: number | undefined,\n /**\n * Whether the version on screen is a signed, sealed copy: locked, so no \"Download with markup\"\n * (and, for the current version, copied comments leave its signed PDF as it is).\n */\n currentSigned = false\n) {\n const { client, notify, saveFile, onDocumentsChanged } = useDocumentTools()\n const documentId = documentData?.external_id\n const currentVersion = documentData?.current_version ?? 1\n const shownVersion = snapshotVersion ?? currentVersion\n const versions = useMemo(() => documentData?.versions ?? [], [documentData?.versions])\n\n // Counts from this session's saves win over the (possibly stale) document record.\n const [localCounts, setLocalCounts] = useState<Record<string, number>>({})\n const countOf = useCallback(\n (n: number) =>\n localCounts[`${documentId}@${n}`] ?? versions.find((v) => v.n === n)?.markup_count ?? 0,\n [localCounts, documentId, versions]\n )\n const hasMarkup = countOf(shownVersion) > 0\n\n const [showOriginal, setShowOriginal] = useState(false)\n useEffect(() => setShowOriginal(false), [documentId, snapshotVersion])\n\n const refresh = useCallback(() => {\n if (!documentId || !onDocumentsChanged) return\n Promise.resolve(onDocumentsChanged([documentId], 'markup')).catch((e: unknown) =>\n console.warn('Could not refresh the document after a markup change', e)\n )\n }, [documentId, onDocumentsChanged])\n\n const onMarkupChange = useCallback(\n (snapshot: MarkupSnapshot) => {\n if (!documentId) return\n const key = `${documentId}@${shownVersion}`\n // The list's \"Download with markup\" and the version entries follow the first/last mark.\n if (countOf(shownVersion) > 0 !== snapshot.count > 0) refresh()\n setLocalCounts((counts) => ({ ...counts, [key]: snapshot.count }))\n },\n [documentId, shownVersion, countOf, refresh]\n )\n\n const downloadMarkup = useCallback(async () => {\n if (!documentId) return\n // A signed version is locked: its markup is never written into its PDF.\n if (currentSigned) {\n notify(SIGNED_LOCKED_REASON, 'info')\n return\n }\n try {\n const { blob, fileName } = await fetchMarkupPdf(\n client,\n documentId,\n snapshotVersion ? snapshotVersion : undefined\n )\n saveFile(blob, fileName)\n } catch (e) {\n notify(e instanceof Error ? e.message : 'The markup could not be downloaded', 'error')\n }\n }, [client, documentId, snapshotVersion, saveFile, notify, currentSigned])\n\n // --- Migration of this browser's layer (arbi:annotations:<docId>) ---\n const [legacyCount, setLegacyCount] = useState(0)\n const [migrating, setMigrating] = useState(false)\n const shared = documentData?.shared\n const loaded = !!documentData\n\n const migrate = useCallback(async () => {\n if (!documentId) return\n const layer = readLegacyLayer(documentId)\n if (!layer) return\n setMigrating(true)\n try {\n const added = await migrateLegacyLayer(documentId, layer, versions, currentVersion, client)\n setLegacyCount(0)\n setLocalCounts({})\n refresh()\n if (added > 0) {\n notify(\n `${added} annotation${added === 1 ? '' : 's'} from this browser saved to the document`,\n 'success',\n {\n description: shared\n ? 'They are now part of the shared markup.'\n : 'They are saved with the document, visible only to you.',\n }\n )\n }\n } catch (e) {\n notify(\n e instanceof Error ? e.message : 'The annotations from this browser could not be saved',\n 'error',\n { description: 'They are still kept in this browser; open the document again to retry.' }\n )\n } finally {\n setMigrating(false)\n }\n }, [client, documentId, versions, currentVersion, refresh, shared, notify])\n\n useEffect(() => {\n if (!documentId || !loaded) return\n const layer = readLegacyLayer(documentId)\n if (!layer) {\n setLegacyCount(0)\n return\n }\n if (layer.annotations.length === 0) {\n forgetLegacyLayer(documentId)\n setLegacyCount(0)\n return\n }\n // A private document is the user's own: its old layer simply becomes its markup. A shared one\n // would show the marks to everyone, so the user decides.\n if (shared) setLegacyCount(layer.annotations.length)\n else void migrate()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [documentId, loaded, shared])\n\n const legacyPrompt: LegacyPrompt | null =\n legacyCount > 0 && !snapshotVersion\n ? {\n count: legacyCount,\n busy: migrating,\n add: () => void migrate(),\n discard: () => {\n if (documentId) forgetLegacyLayer(documentId)\n setLegacyCount(0)\n },\n }\n : null\n\n // --- Markup on an older version (a newer version starts with none) ---\n const [copying, setCopying] = useState(false)\n const olderWithMarkup = versionsWithMarkup(versions)\n .filter((v) => v.n !== currentVersion)\n .sort((a, b) => b.n - a.n)[0]\n const olderNote: OlderMarkupNote | null =\n !snapshotVersion && !hasMarkup && olderWithMarkup\n ? {\n version: olderWithMarkup.n,\n busy: copying,\n signed: currentSigned,\n copy: () => {\n if (!documentId) return\n setCopying(true)\n copyOpenThreads(documentId, olderWithMarkup.n, client)\n .then((n) => {\n if (n > 0) {\n setLocalCounts((c) => ({ ...c, [`${documentId}@${currentVersion}`]: n }))\n refresh()\n }\n notify(\n n > 0\n ? `${n} open comment thread${n === 1 ? '' : 's'} copied to version ${currentVersion}`\n : `Version ${olderWithMarkup.n} has no open comments`,\n n > 0 ? 'success' : 'info',\n // The markup is stored beside the version, so the sealed bytes do not change.\n n > 0 && currentSigned ? { description: SIGNED_UNCHANGED } : undefined\n )\n })\n .catch((e: unknown) =>\n notify(e instanceof Error ? e.message : 'The comments could not be copied', 'error')\n )\n .finally(() => setCopying(false))\n },\n }\n : null\n\n return {\n hasMarkup,\n showOriginal,\n setShowOriginal,\n onMarkupChange,\n downloadMarkup,\n legacyPrompt,\n olderNote,\n }\n}\n","/**\n * Saving a frozen copy: a SEPARATE document derived from the version it was frozen from\n * (`derived_from`, role `redaction` or `annotated`), never a new version of it. The original keeps\n * its place in every list and stays the current version; the copy sits beside it, in the same\n * folder and with the same workspace sharing.\n */\n\nimport type { DocumentToolsEnvironment, DocumentUploadQuery } from './environment'\n\nexport interface FrozenCopySource {\n /** The version on screen, which the copy is derived from. */\n documentId: string\n fileName: string | null | undefined\n shared: boolean\n folder?: string | null\n}\n\nconst baseName = (fileName: string | null | undefined) =>\n (fileName || 'document').replace(/\\.pdf$/i, '')\n\n/** \"Contract.pdf\" becomes \"Contract (redacted).pdf\"; a .txt or .docx keeps its extension inside. */\nexport function frozenCopyName(fileName: string | null | undefined, redacted: boolean): string {\n return `${baseName(fileName)} (${redacted ? 'redacted' : 'annotated'}).pdf`\n}\n\nexport function redactionLogName(fileName: string | null | undefined): string {\n return `${baseName(fileName)} (redaction log).csv`\n}\n\n/** Upload the frozen bytes as a new document derived from `source`; returns its id, if any. */\nexport async function uploadFrozenCopy(\n upload: NonNullable<DocumentToolsEnvironment['uploadDocument']>,\n bytes: Uint8Array,\n source: FrozenCopySource,\n redacted: boolean\n): Promise<string | undefined> {\n const file = new File([bytes as BlobPart], frozenCopyName(source.fileName, redacted), {\n type: 'application/pdf',\n })\n const query: DocumentUploadQuery = {\n derived_from: [source.documentId],\n derived_role: redacted ? 'redaction' : 'annotated',\n shared: source.shared,\n }\n if (source.folder) query.folder = source.folder\n const response = await upload({ file, query })\n return response?.doc_ext_ids?.[0]\n}\n","/**\n * Whether the document on screen can be annotated: only a PDF the viewer is actually showing.\n * Text and Word files are shown as a PDF too, so they qualify; images, audio, video, files that\n * cannot be previewed, drafts and streaming output do not, and neither does a read-only snapshot\n * or a comparison.\n */\n\nexport interface AnnotatableState {\n activeTab: string\n /** The PDF bytes have been fetched. */\n hasPdf: boolean\n isImage: boolean\n isVideo: boolean\n isAudio: boolean\n isDownloadOnly: boolean\n isDraft: boolean\n isStreaming: boolean\n isSnapshot: boolean\n isComparing: boolean\n}\n\nexport function canAnnotate(s: AnnotatableState): boolean {\n return (\n s.activeTab === 'pdf' &&\n s.hasPdf &&\n !s.isImage &&\n !s.isVideo &&\n !s.isAudio &&\n !s.isDownloadOnly &&\n !s.isDraft &&\n !s.isStreaming &&\n !s.isSnapshot &&\n !s.isComparing\n )\n}\n","/**\n * Reactive connectivity from React Query's `onlineManager` (the browser's online events, plus\n * whatever the host feeds it, e.g. a WebSocket). The markup autosave waits while it is false.\n */\n\nimport { useSyncExternalStore } from 'react'\nimport { onlineManager } from '@tanstack/react-query'\n\nexport function useIsOnline(): boolean {\n return useSyncExternalStore(\n (onChange) => onlineManager.subscribe(onChange),\n () => onlineManager.isOnline(),\n () => true\n )\n}\n","/**\n * Electronic signing. The backend (`src/core/esign.py` in ARBI) defines what a signature binds;\n * the helpers mirror the two pieces the browser must reproduce exactly: the statement of intent\n * shown to the signer, and the SHA-256 of the PDF the viewer displayed.\n */\n\nimport { generateUserKeypairs, signMessage, type components } from '@arbidocs/client'\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'\nimport { parseVersionRef } from '../artifacts/versions'\nimport { useDocumentTools, type DocumentToolsClient } from './environment'\n\n/**\n * Who signs: the name only. A role, a firm or a place go on the page as ordinary annotation text,\n * which is not part of the signature.\n */\nexport type SignerDetails = components['schemas']['SignerDetails']\n\n/** Same sentence as `esign.intent_text`; the dialog refuses to sign if the server's differs. */\nexport function intentText(signer: SignerDetails): string {\n return `I, ${signer.name.trim()}, sign this document electronically. I intend this electronic signature to have the same effect as my handwritten signature.`\n}\n\nexport async function sha256Hex(blob: Blob): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(await blob.arrayBuffer()))\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** A signature box drawn on the annotation overlay, as the signing API's placement. */\nexport function toAppearance(box: {\n page: number\n rect: { x: number; y: number; w: number; h: number }\n}): { page: number; x: number; y: number; width: number; height: number } {\n // The layer counts pages from 1, the signing API from 0. Both use fractions of the page as\n // displayed, origin top-left.\n return { page: box.page - 1, x: box.rect.x, y: box.rect.y, width: box.rect.w, height: box.rect.h }\n}\n\n/**\n * The smallest box the backend can draw a legible signature in: the signer's name and the\n * details line shrink to fit, so a box under these fractions of the page is shrunk to near\n * unreadable size. The backend's own default box is 0.40 x 0.10.\n */\nconst MIN_SIGNATURE_BOX = { width: 0.3, height: 0.07 }\n\nexport function isLegibleSignatureBox(rect: { w: number; h: number }): boolean {\n return rect.w >= MIN_SIGNATURE_BOX.width && rect.h >= MIN_SIGNATURE_BOX.height\n}\n\n// ── Signing through the API ─────────────────────────────────────────────────────────────────\n\nexport type SignatureAppearance = components['schemas']['SignatureAppearance']\nexport type SignatureStatusResponse = components['schemas']['SignatureStatusResponse']\nexport type SignatureRecord = components['schemas']['SignatureRecord']\nexport type SignDocumentResponse = components['schemas']['SignDocumentResponse']\n\nconst SIGNATURES_PATH = '/v1/document/{document_ext_id}/signatures'\n/**\n * The same key openapi-react-query gives this request (`['get', path, init]`), so a host that\n * reads or persists the API cache by path treats it like its own queries.\n */\nconst SIGNATURES_KEY = ['get', SIGNATURES_PATH] as const\n\nfunction errorDetail(error: unknown, fallback: string): string {\n const detail = (error as { detail?: unknown } | undefined)?.detail\n return typeof detail === 'string' ? detail : fallback\n}\n\n/** Whether a document version is a signed copy, and its signatures. */\nexport async function fetchDocumentSignatures(\n client: DocumentToolsClient,\n documentRef: string\n): Promise<SignatureStatusResponse> {\n const { docId, version } = parseVersionRef(documentRef)\n const { data, error } = await client.GET(SIGNATURES_PATH, {\n params: { path: { document_ext_id: docId }, ...(version ? { query: { version } } : {}) },\n })\n if (!data) throw new Error(errorDetail(error, 'The signatures could not be read'))\n return data\n}\n\n/**\n * Is a document version a signed copy? `documentId` is a document id (its current version) or a\n * version reference `doc-…@v{n}`. Needs a React Query `QueryClientProvider`.\n */\nexport function useDocumentSignatures(documentId: string | null | undefined, enabled = true) {\n const { client } = useDocumentTools()\n const { docId, version } = parseVersionRef(documentId)\n return useQuery({\n queryKey: [\n ...SIGNATURES_KEY,\n { params: { path: { document_ext_id: docId }, ...(version ? { query: { version } } : {}) } },\n ],\n queryFn: () => fetchDocumentSignatures(client, documentId!),\n enabled: enabled && !!docId,\n staleTime: 60_000,\n })\n}\n\nexport interface SignDocumentVars {\n documentId: string\n /** The PDF bytes the viewer is showing: the signer signs exactly these. */\n pdfBlob: Blob\n email: string\n password: string\n signer: SignerDetails\n /** Where the signature goes; omitted = the backend default (bottom of the last page). */\n appearance?: SignatureAppearance\n /** Draw the signing date under the signature. Default off: only the signature is drawn. */\n includeDate?: boolean\n}\n\n/**\n * Sign a document: the server prepares the statement, the browser checks that it covers the PDF\n * on screen under the wording the signer read, re-derives the user's Ed25519 key from their\n * password and signs it, and the server seals the signed copy as a new version.\n *\n * What is drawn on the page is only the signature (the signer's name as the signature mark) and,\n * with `includeDate`, the date; anyone can click it to open its certificate. A role, a firm or a\n * place go on the page as ordinary annotation text, which is not part of the signature.\n */\nexport async function signDocument(\n client: DocumentToolsClient,\n deploymentDomain: string,\n {\n documentId,\n pdfBlob,\n email,\n password,\n signer,\n appearance,\n includeDate = false,\n }: SignDocumentVars\n): Promise<SignDocumentResponse> {\n const path = { document_ext_id: documentId }\n // One body for both calls: the server refuses a /sign whose include_date (or placement) differs\n // from what was prepared, since what the signature shows is part of what is signed.\n const body = {\n signer: { name: signer.name },\n ...(appearance ? { appearance } : {}),\n include_date: includeDate,\n }\n\n const prepared = await client.POST('/v1/document/{document_ext_id}/sign/prepare', {\n params: { path },\n body,\n })\n if (!prepared.data) throw new Error(errorDetail(prepared.error, 'Could not prepare signing'))\n const { statement, intent, source_sha256, timestamp } = prepared.data\n // Sign only what was on screen, under the wording the signer read.\n if ((await sha256Hex(pdfBlob)) !== source_sha256) {\n throw new Error('The document changed since it was opened. Reopen it and sign again.')\n }\n if (intent !== intentText(signer)) throw new Error('Signing statement mismatch; not signed.')\n\n const { signingKeyPair } = await generateUserKeypairs(email, password, deploymentDomain)\n const signed = await client.POST('/v1/document/{document_ext_id}/sign', {\n params: { path },\n body: { ...body, timestamp, signature: signMessage(statement, signingKeyPair.secretKey) },\n })\n if (!signed.data) throw new Error(errorDetail(signed.error, 'Signing failed'))\n return signed.data\n}\n\n/** The signing mutation. On success the host hears the document changed (`'signed'`). */\nexport function useSignDocument() {\n const env = useDocumentTools()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (vars: SignDocumentVars) => {\n if (!env.deploymentDomain) throw new Error('Signing is not set up: no deployment domain')\n return signDocument(env.client, env.deploymentDomain, vars)\n },\n onSuccess: async (result) => {\n // The signed copy is the document's new current version: the host refreshes its row,\n // versions and rendered PDF, and the signature badge reads again.\n await env.onDocumentsChanged?.([result.doc_ext_id], 'signed')\n await queryClient.invalidateQueries({ queryKey: SIGNATURES_KEY })\n },\n })\n}\n","/**\n * Checking a signature from its reference, without signing in: the public certificate behind the\n * link on a signed PDF's signature (`GET /v1/sign/verify/{reference}`). It names who signed and\n * when, says whether the signed document is unchanged since, and carries the SHA-256 of the signed\n * PDF and of each signed revision, so anyone can check their own copy in the browser (the file is\n * never uploaded). No email addresses and no document content.\n */\n\nimport type { components } from '@arbidocs/client'\nimport { useQuery } from '@tanstack/react-query'\nimport { useDocumentTools, type DocumentToolsClient } from './environment'\nimport { sha256Hex } from './signing'\n\nexport const VERIFY_PATH = '/v1/sign/verify/{reference}'\n\nexport type SignatureVerification = components['schemas']['SignatureVerification']\nexport type VerifiedSignature = components['schemas']['VerifiedSignature']\n\n/** A signature reference as the backend issues them: `sig-` and 128 random bits in hex. */\nconst REFERENCE = /^sig-[0-9a-f]{32}$/\n\nexport function isSignatureReference(reference: string | null | undefined): boolean {\n return !!reference && REFERENCE.test(reference)\n}\n\nexport class SignatureVerificationError extends Error {\n constructor(\n message: string,\n readonly status?: number\n ) {\n super(message)\n this.name = 'SignatureVerificationError'\n }\n}\n\nconst VERIFY_ERRORS: Record<number, string> = {\n 404: 'No signature has this reference.',\n 429: 'Too many checks, try again in a minute.',\n}\n\nexport async function fetchSignatureVerification(\n client: DocumentToolsClient,\n reference: string\n): Promise<SignatureVerification> {\n if (!isSignatureReference(reference)) {\n throw new SignatureVerificationError('This is not a signature reference.')\n }\n const { data, response } = await client.GET(VERIFY_PATH, {\n params: { path: { reference } },\n })\n if (!response.ok || !data) {\n throw new SignatureVerificationError(\n VERIFY_ERRORS[response.status] ?? 'The signature could not be checked right now.',\n response.status\n )\n }\n return data\n}\n\n/** The certificate of a signature reference. Needs a `<DocumentToolsProvider>` (no user). */\nexport function useSignatureVerification(reference: string | null | undefined) {\n const { client } = useDocumentTools()\n return useQuery({\n queryKey: ['get', VERIFY_PATH, { params: { path: { reference } } }],\n queryFn: () => fetchSignatureVerification(client, reference!),\n enabled: !!reference,\n retry: false,\n })\n}\n\n/**\n * What a copy is: the signed document as it stands (`current`), the document as it was when an\n * earlier signer signed it (`earlier`, a counter-signed PDF's earlier revision), or neither.\n */\nexport type CopyMatch =\n { kind: 'current' } | { kind: 'earlier'; signature: VerifiedSignature } | { kind: 'none' }\n\n/** Compare a file with the signed PDF and its signed revisions. Hashed here; nothing is uploaded. */\nexport async function matchSignedCopy(\n file: Blob,\n verification: Pick<SignatureVerification, 'document_sha256' | 'signatures'>\n): Promise<CopyMatch> {\n const hash = await sha256Hex(file)\n if (hash === verification.document_sha256.toLowerCase()) return { kind: 'current' }\n const signature = verification.signatures.find((s) => s.sha256.toLowerCase() === hash)\n return signature ? { kind: 'earlier', signature } : { kind: 'none' }\n}\n"]}
1
+ {"version":3,"sources":["../../src/document-tools/environment.tsx","../../src/document-tools/document-pdf.ts","../../src/document-tools/production.ts","../../src/document-tools/markup-store.ts","../../src/document-tools/markup-transfer.ts","../../src/document-tools/markup-download.ts","../../src/document-tools/useDocumentMarkup.ts","../../src/document-tools/frozen-copy.ts","../../src/document-tools/can-annotate.ts","../../src/document-tools/useIsOnline.ts","../../src/document-tools/signing.ts","../../src/document-tools/verification.ts"],"names":["useMemo","useQuery"],"mappings":";;;;;;;;;;;;;;;AA+DO,SAAS,kBAAkB,KAAA,EAAoC;AACpE,EAAA,MAAM,MAAA,GAAS,IAAI,eAAA,EAAgB;AACnC,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAChD,IAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,MAAA,EAAW;AAC3C,IAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,CAAM,OAAA,CAAQ,KAAK,IAAI,KAAA,GAAQ,CAAC,KAAK,CAAA,EAAG,MAAA,CAAO,MAAA,CAAO,GAAA,EAAK,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,EAC5F;AAC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the one place\n * the tools reach the app. They never import a store, a router, a toast library or app API code;\n * the host passes what it has to `<DocumentToolsProvider>` and every optional field has a default.\n *\n * `client` is an openapi-fetch client for the ARBI API (`ArbiClient['fetch']` from\n * `@arbidocs/client`, or `arbi.getClient().fetch` from an `@arbidocs/sdk` `Arbi`), signed in with the\n * user's session; it carries the auth.\n */\n\nimport { createContext, useContext, useMemo, type ReactNode } from 'react'\nimport type { ArbiClient, operations } from '@arbidocs/client'\nimport { useDeploymentDomain } from '../useArbi'\n\nexport type DocumentToolsClient = ArbiClient['fetch']\n\nexport type DocumentToolsNoticeKind = 'success' | 'error' | 'info' | 'warning'\n\nexport interface DocumentToolsNoticeOptions {\n /** A second line under the message. */\n description?: string\n /** One action button on the notice (\"Email it\"). */\n action?: { label: string; onClick: () => void }\n}\n\nexport type DocumentToolsNotify = (\n message: string,\n kind: DocumentToolsNoticeKind,\n options?: DocumentToolsNoticeOptions\n) => void\n\nexport interface DocumentToolsUser {\n /** The name marks are authored as and the signer's name is prefilled with. */\n name: string\n /** The sign-in email: signing re-derives the user's key from it and the password. */\n email?: string | null\n}\n\n/** What changed about a document, so the host can refresh its own lists and caches. */\nexport type DocumentChange =\n /** A version's markup got its first mark or lost its last one. */\n | 'markup'\n /** A signature was added: the document has a new current version. */\n | 'signed'\n /** A new document was made from it (a frozen copy). The ids are the NEW documents. */\n | 'copy'\n\n/**\n * The `/v1/document/upload` query, typed from the API schema: `derived_from` is a list (a\n * production set is derived from every document in it), `shared` a boolean.\n */\nexport type DocumentUploadQuery = NonNullable<operations['upload_documents']['parameters']['query']>\n\nexport interface DocumentUploadRequest {\n file: File\n /** `/v1/document/upload` query: `derived_from`, `derived_role`, `shared`, `folder`. */\n query: DocumentUploadQuery\n}\n\n/**\n * The upload query as a URL query string, for a host that posts the upload itself (an XHR with\n * progress): a list repeats its key (`derived_from=a&derived_from=b`), empty values are left out.\n */\nexport function uploadQueryString(query: DocumentUploadQuery): string {\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (value === null || value === undefined) continue\n for (const item of Array.isArray(value) ? value : [value]) params.append(key, String(item))\n }\n return params.toString()\n}\n\nexport interface DocumentToolsEnvironment {\n client: DocumentToolsClient\n /**\n * The deployment domain the user's keys are derived for. Needed for signing. Default: the one\n * the enclosing `<ArbiProvider>`'s `Arbi` computes (`arbi.getDeploymentDomain()`), if any.\n */\n deploymentDomain?: string\n /** The signed-in user; marks are authored as \"You\" without one, and signing is unavailable. */\n user?: DocumentToolsUser | null\n /** Surface a transient message. Default: none (errors still show inline where they can). */\n notify?: DocumentToolsNotify\n /** Open a document or a version reference (`doc-…@v2`): the copy just made, the signed copy. */\n openDocument?: (documentRef: string) => void\n /**\n * Documents changed on the server (see {@link DocumentChange}); refresh the host's lists. The\n * tools wait for it before opening the document, so a copy is listed when it opens.\n */\n onDocumentsChanged?: (documentIds: string[], change: DocumentChange) => void | Promise<void>\n /** Upload a derived copy. Default: `POST /v1/document/upload` through `client`. */\n uploadDocument?: (\n request: DocumentUploadRequest\n ) => Promise<{ doc_ext_ids?: string[] } | undefined>\n /** Save a file to the user's computer. Default: a temporary download link. */\n saveFile?: (blob: Blob, fileName: string) => void\n /** Email a document (offered once it is signed). Omitted: no \"Email it\". */\n emailDocument?: (documentRef: string) => void\n /**\n * The public page that checks a signature (the certificate) in this app. When given, \"View\n * certificate\" opens it in preference to the backend's `certificate_url` (which is on the\n * deployment domain, like the link embedded in the signed PDF). Without it: the backend's\n * `certificate_url`, else `/verify/{reference}` on this origin.\n */\n certificateUrl?: (reference: string) => string\n}\n\n/** The environment with every default filled in. */\nexport interface ResolvedDocumentToolsEnvironment extends DocumentToolsEnvironment {\n notify: DocumentToolsNotify\n saveFile: (blob: Blob, fileName: string) => void\n uploadDocument: (\n request: DocumentUploadRequest\n ) => Promise<{ doc_ext_ids?: string[] } | undefined>\n}\n\n/** Save a blob through a temporary `<a download>`. */\nexport function downloadBlob(blob: Blob, fileName: string): void {\n const url = URL.createObjectURL(blob)\n const a = document.createElement('a')\n a.href = url\n a.download = fileName\n document.body.appendChild(a)\n a.click()\n a.remove()\n setTimeout(() => URL.revokeObjectURL(url), 1000)\n}\n\n/** The default upload: multipart `files` to `/v1/document/upload` through the API client. */\nexport function clientUpload(client: DocumentToolsClient) {\n return async ({ file, query }: DocumentUploadRequest) => {\n const formData = new FormData()\n formData.append('files', file)\n const { data, response } = await client.POST('/v1/document/upload', {\n params: { query },\n // The schema types the multipart body as `{ files: string[] }`; the FormData is sent as is.\n body: formData as unknown as { files: string[] },\n bodySerializer: () => formData,\n })\n if (!response.ok) throw new Error(`Upload failed with status ${response.status}`)\n return data\n }\n}\n\nexport function defaultCertificateUrl(reference: string): string {\n const origin = typeof location === 'undefined' ? '' : location.origin\n return `${origin}/verify/${encodeURIComponent(reference)}`\n}\n\n/**\n * Where \"View certificate\" goes for a signature: the host's `certificateUrl(reference)` when it\n * gives one, else the `certificate_url` the backend returned, else `/verify/{reference}` here.\n */\nexport function certificateLink(\n signature: { reference: string; certificate_url?: string | null },\n certificateUrl?: (reference: string) => string\n): string {\n if (certificateUrl) return certificateUrl(signature.reference)\n return signature.certificate_url || defaultCertificateUrl(signature.reference)\n}\n\nconst DocumentToolsContext = createContext<ResolvedDocumentToolsEnvironment | null>(null)\n\nexport interface DocumentToolsProviderProps extends DocumentToolsEnvironment {\n children: ReactNode\n}\n\nexport function DocumentToolsProvider({ children, ...env }: DocumentToolsProviderProps) {\n const arbiDeploymentDomain = useDeploymentDomain()\n const {\n client,\n deploymentDomain,\n user,\n notify,\n openDocument,\n onDocumentsChanged,\n uploadDocument,\n saveFile,\n emailDocument,\n certificateUrl,\n } = env\n const value = useMemo<ResolvedDocumentToolsEnvironment>(\n () => ({\n client,\n deploymentDomain: deploymentDomain ?? arbiDeploymentDomain,\n user,\n openDocument,\n onDocumentsChanged,\n emailDocument,\n notify: notify ?? (() => {}),\n saveFile: saveFile ?? downloadBlob,\n uploadDocument: uploadDocument ?? clientUpload(client),\n certificateUrl,\n }),\n [\n client,\n deploymentDomain,\n arbiDeploymentDomain,\n user,\n notify,\n openDocument,\n onDocumentsChanged,\n uploadDocument,\n saveFile,\n emailDocument,\n certificateUrl,\n ]\n )\n return <DocumentToolsContext.Provider value={value}>{children}</DocumentToolsContext.Provider>\n}\n\n/** The host's environment, or `null` outside a `<DocumentToolsProvider>`. */\nexport function useOptionalDocumentTools(): ResolvedDocumentToolsEnvironment | null {\n return useContext(DocumentToolsContext)\n}\n\n/** The host's environment; throws outside a `<DocumentToolsProvider>`. */\nexport function useDocumentTools(): ResolvedDocumentToolsEnvironment {\n const env = useContext(DocumentToolsContext)\n if (!env) throw new Error('The document tools must be used within a <DocumentToolsProvider>')\n return env\n}\n","/**\n * A document's bytes, through the host's API client: the PDF the viewer and the tools draw on\n * (`/view`: the file itself for a PDF, its PDF rendering for a Word or text file) and the stored\n * file (`/download`). Either takes a document id or a version reference `doc-…@v{n}`.\n */\n\nimport { parseVersionRef } from '../artifacts/versions'\nimport type { DocumentToolsClient } from './environment'\n\nexport interface DocumentFetchOptions {\n /** The version to fetch. Default: the one `documentRef` names, else the current version. */\n version?: number | null\n signal?: AbortSignal\n}\n\n/** A document's bytes could not be fetched; `status` is the HTTP status. */\nexport class DocumentFetchError extends Error {\n readonly status: number\n constructor(message: string, status: number) {\n super(message)\n this.name = 'DocumentFetchError'\n this.status = status\n }\n}\n\nasync function fetchDocumentBytes(\n client: DocumentToolsClient,\n endpoint: '/v1/document/{document_ext_id}/view' | '/v1/document/{document_ext_id}/download',\n documentRef: string,\n options: DocumentFetchOptions,\n headers: Record<string, string>,\n what: string\n): Promise<Blob> {\n const ref = parseVersionRef(documentRef)\n const version = options.version ?? ref.version\n const { data, response } = await client.GET(endpoint, {\n params: { path: { document_ext_id: ref.docId }, query: version ? { version } : {} },\n headers,\n parseAs: 'blob',\n signal: options.signal,\n })\n if (!response.ok || !(data instanceof Blob)) {\n throw new DocumentFetchError(\n `${what} could not be loaded (${response.status})`,\n response.status\n )\n }\n return data\n}\n\n/**\n * The PDF of a document version: `GET /v1/document/{id}/view?version=` with\n * `Accept: application/pdf`. Throws a {@link DocumentFetchError} when there is none (yet).\n */\nexport function fetchDocumentPdf(\n client: DocumentToolsClient,\n documentRef: string,\n options: DocumentFetchOptions = {}\n): Promise<Blob> {\n return fetchDocumentBytes(\n client,\n '/v1/document/{document_ext_id}/view',\n documentRef,\n options,\n { Accept: 'application/pdf' },\n 'The PDF'\n )\n}\n\n/** The stored file of a document version, as uploaded: `GET /v1/document/{id}/download`. */\nexport function fetchDocumentFile(\n client: DocumentToolsClient,\n documentRef: string,\n options: DocumentFetchOptions = {}\n): Promise<Blob> {\n return fetchDocumentBytes(\n client,\n '/v1/document/{document_ext_id}/download',\n documentRef,\n options,\n {},\n 'The file'\n )\n}\n","/**\n * Production sets: number the selected documents with Bates labels (optionally a QR code back to\n * each document and an index page) and save the result back to the workspace. The dialog is\n * `ProductionSetDialog` in `@arbidocs/blocks/document-tools`; this is its data side.\n *\n * A PDF is numbered as stored (`/download`). Any other document is numbered through its PDF\n * rendition (`/view`, what the viewer shows for a Word or text file); one without a rendition is\n * left out. Saved results are new documents derived from their sources (role `production`) in a\n * Productions folder, shared with the workspace only if every source is. The originals never\n * change.\n *\n * pdf-lib (the numbering) is loaded only when a production is built, so importing this module\n * stays as light as the rest of the document tools.\n */\n\nimport type { components } from '@arbidocs/client'\nimport type { ProductionChoices } from '../annotations/ProductionDialog'\nimport type { BundleFile, BundleIndexEntry, BundleItem } from '../annotations/freeze/bundle'\nimport { DocumentFetchError, fetchDocumentFile, fetchDocumentPdf } from './document-pdf'\nimport type {\n DocumentToolsClient,\n DocumentToolsEnvironment,\n DocumentUploadQuery,\n} from './environment'\n\n/** The fields of a document record (`DocResponse`) a production uses. */\nexport type ProductionSource = Pick<\n components['schemas']['DocResponse'],\n 'external_id' | 'file_name' | 'file_type' | 'shared'\n> & { doc_metadata?: { title?: string | null } | null }\n\nexport const PRODUCTIONS_FOLDER = 'Productions'\n\nconst extensionOf = (fileName: string | null | undefined) => {\n const name = (fileName ?? '').toLowerCase()\n const dot = name.lastIndexOf('.')\n return dot < 0 ? '' : name.slice(dot + 1)\n}\n\n/** Media, archives and design files: no PDF version to number. */\nconst NO_RENDITION_EXTENSIONS = new Set(\n [\n // images\n 'jpg jpeg png gif bmp tiff tif webp heic',\n // video and audio\n 'mp4 mpeg mpg webm mov avi mkv mp3 wav m4a aac ogg flac',\n // archives, binaries, design files\n 'zip rar 7z tar gz exe bin dmg iso apk msi dll so psd ai sketch',\n ]\n .join(' ')\n .split(' ')\n)\n\nexport const isPdfDocument = (doc: ProductionSource) =>\n /pdf/i.test(doc.file_type ?? '') || extensionOf(doc.file_name) === 'pdf'\n\n/** True for a document with no PDF version to number (media, archives and the like). */\nexport const hasNoRendition = (doc: ProductionSource) =>\n !isPdfDocument(doc) && NO_RENDITION_EXTENSIONS.has(extensionOf(doc.file_name))\n\n/** The name a document goes by in the dialog and the index: its title, else its file name. */\nexport const productionDocumentName = (doc: ProductionSource) =>\n doc.doc_metadata?.title || doc.file_name || doc.external_id\n\nconst isPdfBytes = (bytes: Uint8Array) =>\n bytes.length > 4 && String.fromCharCode(...bytes.subarray(0, 5)) === '%PDF-'\n\n/**\n * The PDF to number for `doc`: the file itself, or the PDF version of anything else. `null` when a\n * non-PDF has no PDF version (yet), so it is left out; a PDF that cannot be downloaded throws.\n */\nexport async function fetchProductionPdf(\n client: DocumentToolsClient,\n doc: ProductionSource\n): Promise<Uint8Array | null> {\n const pdf = isPdfDocument(doc)\n let blob: Blob\n try {\n blob = await (pdf ? fetchDocumentFile : fetchDocumentPdf)(client, doc.external_id)\n } catch (e) {\n if (!pdf && e instanceof DocumentFetchError) return null\n throw e\n }\n const bytes = new Uint8Array(await blob.arrayBuffer())\n return pdf || isPdfBytes(bytes) ? bytes : null\n}\n\nconst safeName = (name: string) => name.replace(/[\\\\/:*?\"<>|]+/g, '_').trim()\n\n/** \"Production ACME-000001-ACME-000042\": names the files and folder of one production. */\nexport function productionTitle(firstLabel: string, lastLabel: string): string {\n return safeName(`Production ${firstLabel}-${lastLabel}`)\n}\n\n/** Where a production is saved: the Productions folder, or a folder of its own per document. */\nexport function productionFolder(title: string, merged: boolean): string {\n return merged ? PRODUCTIONS_FOLDER : `${PRODUCTIONS_FOLDER}/${title}`\n}\n\n/** In the workspace a per-document file says which range it holds, beside its original. */\nexport function productionFileName(file: BundleFile, title: string): string {\n if (!file.firstLabel) return `${title} index.pdf`\n return `${file.name.replace(/\\.pdf$/i, '')} (${file.firstLabel}-${file.lastLabel}).pdf`\n}\n\nconst csvCell = (value: string | number) => `\"${String(value).replace(/\"/g, '\"\"')}\"`\n\n/** The `index.csv` of a per-document production: every document with its file and range. */\nexport function productionIndexCsv(index: readonly BundleIndexEntry[]): string {\n const rows = index.map((e) =>\n [e.documentId, e.name, e.file, e.pages, e.firstLabel, e.lastLabel].map(csvCell).join(',')\n )\n return ['document_id,name,file,pages,first_label,last_label', ...rows].join('\\n')\n}\n\nexport interface ProductionUpload {\n name: string\n bytes: Uint8Array\n /** The documents this file was made from. */\n sources: ProductionSource[]\n}\n\n/** Save each file as a new workspace document derived from its sources; returns the new ids. */\nexport async function saveProductionFiles(\n upload: NonNullable<DocumentToolsEnvironment['uploadDocument']>,\n files: readonly ProductionUpload[],\n folder: string\n): Promise<string[]> {\n const ids: string[] = []\n for (const file of files) {\n const query: DocumentUploadQuery = {\n derived_from: file.sources.map((doc) => doc.external_id),\n derived_role: 'production',\n shared: file.sources.every((doc) => doc.shared),\n folder,\n }\n const response = await upload({\n file: new File([file.bytes as BlobPart], file.name, { type: 'application/pdf' }),\n query,\n })\n ids.push(...(response?.doc_ext_ids ?? []))\n }\n return ids\n}\n\nexport interface BuildProductionOptions {\n /** The link a document's QR code opens (the document in the host app). */\n documentUrl: (documentId: string) => string\n /** Who produced the set; recorded in a merged file's metadata. */\n author?: string\n onProgress?: (done: number, total: number) => void\n}\n\nexport interface BuiltProduction {\n title: string\n merged: boolean\n /** The numbered files: one merged PDF (named after its range), or one per document (+ index). */\n files: BundleFile[]\n index: BundleIndexEntry[]\n /** The documents numbered, in order. */\n included: ProductionSource[]\n /** Documents left out because they have no PDF version yet. */\n noRendition: ProductionSource[]\n /** The files as they are saved to the workspace, each with the documents it was made from. */\n uploads: ProductionUpload[]\n folder: string\n}\n\n/**\n * Fetch each document's PDF (in `choices.order`) and number the set. Throws when none of the\n * documents has a PDF version, or when a PDF cannot be fetched.\n */\nexport async function buildProduction(\n client: DocumentToolsClient,\n documents: readonly ProductionSource[],\n choices: ProductionChoices,\n options: BuildProductionOptions\n): Promise<BuiltProduction> {\n const byId = new Map(documents.map((doc) => [doc.external_id, doc]))\n const included: ProductionSource[] = []\n const noRendition: ProductionSource[] = []\n const items: BundleItem[] = []\n for (const doc of choices.order.flatMap((id) => byId.get(id) ?? [])) {\n const bytes = await fetchProductionPdf(client, doc)\n if (!bytes) {\n noRendition.push(doc)\n continue\n }\n included.push(doc)\n items.push({\n name: productionDocumentName(doc),\n documentId: doc.external_id,\n bytes,\n qrUrl: options.documentUrl(doc.external_id),\n })\n }\n if (items.length === 0) {\n throw new Error('None of these documents has a PDF version to number yet.')\n }\n\n const { buildBundle } = await import('../annotations/freeze/bundle')\n const result = await buildBundle(items, {\n layout: choices.layout,\n bates: {\n prefix: choices.prefix,\n start: choices.start,\n digits: choices.digits,\n corner: choices.corner,\n },\n qr: choices.qr,\n // The QR code sits in the bottom corner the label is not in.\n qrCorner: choices.corner.endsWith('left') ? 'bottom-right' : 'bottom-left',\n indexPage: choices.indexPage,\n author: options.author,\n onProgress: options.onProgress,\n })\n\n const title = productionTitle(\n result.index[0].firstLabel,\n result.index[result.index.length - 1].lastLabel\n )\n const merged = choices.layout === 'merged'\n // A merged file is named after its range; per-document files keep their document names.\n const files = merged ? [{ ...result.files[0], name: `${title}.pdf` }] : result.files\n const sourceOf = new Map(result.index.map((e) => [e.file, byId.get(e.documentId)!]))\n const uploads = files.map((file) => ({\n name: merged ? file.name : productionFileName(file, title),\n bytes: file.bytes,\n // The merged file (and a separate index) is made from every document; each per-document\n // file from its own.\n sources: merged || !sourceOf.has(file.name) ? included : [sourceOf.get(file.name)!],\n }))\n return {\n title,\n merged,\n files,\n index: result.index,\n included,\n noRendition,\n uploads,\n folder: productionFolder(title, merged),\n }\n}\n","/**\n * The annotation store for a document version's MARKUP on the server: `GET`/`PUT\n * /v1/document/{id}/markup`. The server keeps the marks as native PDF annotations in an encrypted\n * `{doc}-markup.pdf` next to the version (same document id, the document's own privacy); this store\n * only moves the layer and its revision.\n *\n * Optimistic concurrency: every save names the revision it started from. When someone else saved\n * first the server answers 409; the store then re-reads the latest layer, merges it with ours by\n * annotation id (`mergeLayers`: union, last edit wins per mark, replies unioned, our deletions\n * stay deleted) and saves again. The merged layer is returned so the viewer shows their marks too.\n *\n * Deletions are tracked as tombstones for the session: an id this session has seen that is no\n * longer in the layer it saves was deleted here, and a concurrent edit elsewhere cannot bring it\n * back.\n */\n\nimport {\n AnnotationStoreOfflineError,\n LAYER_SCHEMA_VERSION,\n mergeLayers,\n parseLayer,\n type AnnotationLayer,\n type AnnotationStore,\n} from '../annotations'\nimport type { DocumentToolsClient } from './environment'\n\n/** How many times a save re-reads and merges after a 409 before giving up (each is a real race). */\nexport const MAX_MERGE_ATTEMPTS = 5\n/** Below this many bytes a save uses `keepalive`, so it completes even if the page unloads. */\nconst KEEPALIVE_LIMIT = 60_000\n\nexport interface MarkupSnapshot {\n revision: number\n count: number\n canEdit: boolean\n}\n\nexport interface MarkupStoreOptions {\n /** The version the markup belongs to; omitted = the document's current version. */\n version?: number\n /** The ARBI API client (see `DocumentToolsEnvironment.client`). */\n client: DocumentToolsClient\n /** After every successful save: the new revision and how many marks the markup holds. */\n onSaved?: (snapshot: MarkupSnapshot) => void\n}\n\nexport interface MarkupStore extends AnnotationStore {\n snapshot(): MarkupSnapshot\n}\n\ninterface ServerLayer {\n revision: number\n layer: AnnotationLayer\n canEdit: boolean\n}\n\nexport class MarkupStoreError extends Error {\n constructor(\n message: string,\n readonly status?: number\n ) {\n super(message)\n this.name = 'MarkupStoreError'\n }\n}\n\nconst detailOf = (error: unknown, fallback: string) => {\n const detail = (error as { detail?: unknown } | undefined)?.detail\n return typeof detail === 'string' ? detail : fallback\n}\n\n/** A request that never reached the server (no network, DNS, CORS) is \"offline\", not a failure. */\nasync function call<T>(request: () => Promise<T>): Promise<T> {\n try {\n return await request()\n } catch (e) {\n if (e instanceof TypeError || (typeof navigator !== 'undefined' && !navigator.onLine)) {\n throw new AnnotationStoreOfflineError()\n }\n throw e\n }\n}\n\nexport function createMarkupStore({ version, client, onSaved }: MarkupStoreOptions): MarkupStore {\n let revision = 0\n let count = 0\n let canEdit = false\n /** The layer as last read from or written to the server: the base of a merge. */\n let base: AnnotationLayer | null = null\n /** Every mark id this session has held: one missing from a save was deleted here. */\n const seen = new Set<string>()\n const remember = (layer: AnnotationLayer) => {\n for (const a of layer.annotations) seen.add(a.id)\n }\n const query = version ? { version } : {}\n\n async function read(documentId: string, ifNoneMatch?: number): Promise<ServerLayer | null> {\n const { data, error, response } = await call(() =>\n client.GET('/v1/document/{document_ext_id}/markup', {\n params: { path: { document_ext_id: documentId }, query },\n headers: ifNoneMatch === undefined ? undefined : { 'If-None-Match': `\"${ifNoneMatch}\"` },\n })\n )\n if (response.status === 304) return null\n if (error || !data) {\n throw new MarkupStoreError(\n detailOf(error, `The markup could not be loaded (${response.status})`),\n response.status\n )\n }\n const layer = parseLayer({\n schema: LAYER_SCHEMA_VERSION,\n documentId,\n annotations: data.annotations ?? [],\n updatedAt: data.updated_at ?? new Date().toISOString(),\n })\n return { revision: data.revision ?? 0, layer, canEdit: !!data.can_edit }\n }\n\n function adopt(server: ServerLayer) {\n revision = server.revision\n canEdit = server.canEdit\n base = server.layer\n count = server.layer.annotations.length\n remember(server.layer)\n }\n\n async function put(layer: AnnotationLayer, from: number) {\n return call(() =>\n client.PUT('/v1/document/{document_ext_id}/markup', {\n params: { path: { document_ext_id: layer.documentId }, query },\n headers: { 'If-Match': `\"${from}\"` },\n body: { annotations: layer.annotations as never, base_revision: from },\n // A save started as the page closes must outlive it; browsers cap such bodies at 64 KB.\n keepalive: JSON.stringify(layer.annotations).length < KEEPALIVE_LIMIT,\n })\n )\n }\n\n return {\n snapshot: () => ({ revision, count, canEdit }),\n canEdit: () => canEdit,\n\n async load(documentId) {\n const server = await read(documentId)\n if (!server) throw new MarkupStoreError('The markup could not be loaded')\n adopt(server)\n return server.layer\n },\n\n async save(layer) {\n remember(layer)\n let mine = layer\n for (let attempt = 0; attempt < MAX_MERGE_ATTEMPTS; attempt++) {\n const { data, error, response } = await put(mine, revision)\n if (response.ok && data) {\n revision = data.revision\n count = data.count\n base = mine\n remember(mine)\n onSaved?.({ revision, count, canEdit })\n return mine\n }\n if (response.status === 409) {\n // Someone saved first: their layer, merged with ours, is what we save next.\n const latest = await read(layer.documentId)\n if (!latest) throw new MarkupStoreError('The markup could not be re-read')\n const deleted = new Set(\n [...seen].filter((id) => !mine.annotations.some((a) => a.id === id))\n )\n const merged = mergeLayers({ base, mine, theirs: latest.layer, deleted })\n revision = latest.revision\n canEdit = latest.canEdit\n base = latest.layer\n remember(latest.layer)\n mine = merged\n continue\n }\n if (response.status === 403) canEdit = false\n throw new MarkupStoreError(\n detailOf(error, `The markup could not be saved (${response.status})`),\n response.status\n )\n }\n throw new MarkupStoreError('The markup keeps changing; it will be saved on the next edit')\n },\n\n async pull(documentId) {\n const server = await read(documentId, revision)\n if (!server || server.revision === revision) return null\n adopt(server)\n return server.layer\n },\n }\n}\n","/**\n * Moving marks INTO a version's markup without the viewer: the one-time migration of layers kept in\n * this browser before markup lived on the server, and \"copy open comments\" from an older version's\n * markup onto the current one (a new version — signed, synced from Drive, saved from Word — starts\n * with an empty markup; redactions never carry over).\n *\n * Both are unions by annotation id, so running them twice adds nothing twice.\n */\n\nimport {\n LAYER_SCHEMA_VERSION,\n emptyLayer,\n mergeLayers,\n parseLayer,\n type Annotation,\n type AnnotationLayer,\n} from '../annotations'\nimport type { DocumentToolsClient } from './environment'\nimport { createMarkupStore } from './markup-store'\n\nexport const LEGACY_LAYER_PREFIX = 'arbi:annotations:'\n\nexport interface VersionInfo {\n n: number\n created_at?: string | null\n markup_count?: number | null\n}\n\nfunction storage(): Storage | undefined {\n try {\n return typeof localStorage === 'undefined' ? undefined : localStorage\n } catch {\n return undefined\n }\n}\n\n/** The layer this browser kept for a document before markup moved to the server, if any. */\nexport function readLegacyLayer(documentId: string): AnnotationLayer | null {\n try {\n const raw = storage()?.getItem(LEGACY_LAYER_PREFIX + documentId)\n if (!raw) return null\n return parseLayer(JSON.parse(raw))\n } catch {\n return null // unreadable: nothing worth migrating\n }\n}\n\nexport function forgetLegacyLayer(documentId: string): void {\n try {\n storage()?.removeItem(LEGACY_LAYER_PREFIX + documentId)\n } catch {\n // storage blocked: nothing to forget\n }\n}\n\n/**\n * Which version each legacy mark belongs to: the version that was current when it was made. A\n * document's id is the id of its first version (older layers were made on it); a layer made after\n * the versions moved inside the document was made on whatever version was then current.\n */\nexport function marksByVersion(\n layer: AnnotationLayer,\n versions: VersionInfo[]\n): Map<number, Annotation[]> {\n const sorted = [...versions].sort((a, b) => a.n - b.n)\n const out = new Map<number, Annotation[]>()\n for (const mark of layer.annotations) {\n const at = Date.parse(mark.createdAt)\n let target = sorted[0]?.n ?? 1\n for (const v of sorted) {\n const created = v.created_at ? Date.parse(v.created_at) : Number.NaN\n if (!Number.isNaN(created) && !Number.isNaN(at) && created <= at) target = v.n\n }\n out.set(target, [...(out.get(target) ?? []), mark])\n }\n return out\n}\n\n/** Add marks to one version's markup (union by id); returns how many were new. */\nexport async function addToMarkup(\n documentId: string,\n version: number | undefined,\n marks: Annotation[],\n client: DocumentToolsClient\n): Promise<number> {\n const store = createMarkupStore({ version, client })\n const current = await store.load(documentId)\n const incoming: AnnotationLayer = {\n ...emptyLayer(documentId, new Date().toISOString()),\n annotations: marks,\n }\n // Theirs (the server) wins any tie: a mark already in the markup is never overwritten by an\n // older browser copy of it.\n const merged = mergeLayers({ base: null, mine: current, theirs: incoming })\n const added = merged.annotations.length - current.annotations.length\n if (added > 0) await store.save(parseLayer({ ...merged, schema: LAYER_SCHEMA_VERSION }))\n return added\n}\n\n/**\n * Migrate this browser's layer for a document into its markup, version by version, then forget\n * the browser copy. Throws (and keeps the browser copy) if any version could not be saved.\n */\nexport async function migrateLegacyLayer(\n documentId: string,\n layer: AnnotationLayer,\n versions: VersionInfo[],\n currentVersion: number,\n client: DocumentToolsClient\n): Promise<number> {\n let added = 0\n for (const [n, marks] of marksByVersion(layer, versions.length ? versions : [{ n: 1 }])) {\n added += await addToMarkup(documentId, n === currentVersion ? undefined : n, marks, client)\n }\n forgetLegacyLayer(documentId)\n return added\n}\n\n/** The unresolved comment threads (with replies) of a version's markup. */\nexport async function openThreadsOf(\n documentId: string,\n version: number,\n client: DocumentToolsClient\n): Promise<Annotation[]> {\n const layer = await createMarkupStore({ version, client }).load(documentId)\n return layer.annotations.filter((a) => a.kind === 'comment' && !a.resolved)\n}\n\n/** Copy the open comment threads of an older version onto the current version's markup. */\nexport async function copyOpenThreads(\n documentId: string,\n fromVersion: number,\n client: DocumentToolsClient\n): Promise<number> {\n const threads = await openThreadsOf(documentId, fromVersion, client)\n if (!threads.length) return 0\n return addToMarkup(documentId, undefined, threads, client)\n}\n\n/** Version entries of a document as the API returns them (`DocResponse.versions`). */\nexport function versionsWithMarkup(versions: VersionInfo[] | null | undefined): VersionInfo[] {\n return (versions ?? []).filter((v) => (v.markup_count ?? 0) > 0)\n}\n","/**\n * \"Download with markup\": a document version's markup PDF, the PDF with its annotations as native\n * PDF annotations (comments, highlights, stamps, unapplied redactions), which Acrobat and Preview\n * show. The plain Download serves the original. Kept apart from the annotation layer code so a\n * documents list can offer it without loading the annotation tools.\n *\n * A SIGNED version is locked: nothing but a further signature changes it. Its markup stays in the\n * separate markup layer (a title beside the signature, say) and is never written into its PDF, so\n * it has no \"Download with markup\"; the plain Download is the signed file as it is.\n */\n\nimport type { DocumentToolsClient } from './environment'\n\ninterface DocumentVersions {\n current_version?: number | null\n versions?: Array<{ n: number; markup_count?: number | null; reason?: string | null }> | null\n}\n\n/** Why \"Download with markup\" is off for a signed version. */\nexport const SIGNED_LOCKED_REASON =\n \"Signed documents can't be changed — download the signed file instead\"\n\n/** Whether a version (default: the current one) is a signed copy, per its version entry. */\nexport function isSignedVersion(doc: DocumentVersions, version?: number): boolean {\n const n = version ?? doc.current_version ?? 1\n return (doc.versions ?? []).some((v) => v.n === n && v.reason === 'signed')\n}\n\nexport class MarkupDownloadError extends Error {\n constructor(\n message: string,\n readonly status?: number\n ) {\n super(message)\n this.name = 'MarkupDownloadError'\n }\n}\n\n/** Whether a document's current version has markup (per its version entries). */\nexport function currentHasMarkup(doc: DocumentVersions): boolean {\n const n = doc.current_version ?? 1\n return (doc.versions ?? []).some((v) => v.n === n && (v.markup_count ?? 0) > 0)\n}\n\n/** Fetch a version's markup PDF (default: the current version's). */\nexport async function fetchMarkupPdf(\n client: DocumentToolsClient,\n documentId: string,\n version?: number\n): Promise<{ blob: Blob; fileName: string }> {\n const { data, response } = await client.GET('/v1/document/{document_ext_id}/markup/pdf', {\n params: { path: { document_ext_id: documentId }, query: version ? { version } : {} },\n parseAs: 'blob',\n })\n if (!response.ok || !data) {\n throw new MarkupDownloadError(\n response.status === 404\n ? 'This document has no markup yet'\n : // The server refuses a signed version: its PDF takes no more changes.\n response.status === 409\n ? SIGNED_LOCKED_REASON\n : 'The markup could not be downloaded',\n response.status\n )\n }\n const disposition = response.headers.get('content-disposition') ?? ''\n const utf8 = /filename\\*=UTF-8''([^;]+)/i.exec(disposition)?.[1]\n const plain = /filename=\"([^\"]+)\"/i.exec(disposition)?.[1]\n const fileName = utf8 ? decodeURIComponent(utf8) : (plain ?? 'markup.pdf')\n return { blob: data as Blob, fileName }\n}\n","/**\n * Markup state for the document page: whether the version on screen has markup (so the viewer\n * opens on it, the default view), the \"Show original\" toggle, \"Download with markup\", the one-time\n * migration of this browser's old annotation layer, and the note shown when the markup is on an\n * older version (with \"copy open comments\").\n *\n * Whether a version has markup comes from the document's version entries (`markup_count`), kept\n * current by the viewer's own saves (`onMarkupChange`) until the document is refetched.\n */\n\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useDocumentTools } from './environment'\nimport type { MarkupSnapshot } from './markup-store'\nimport { SIGNED_LOCKED_REASON, fetchMarkupPdf } from './markup-download'\nimport {\n copyOpenThreads,\n forgetLegacyLayer,\n migrateLegacyLayer,\n readLegacyLayer,\n versionsWithMarkup,\n type VersionInfo,\n} from './markup-transfer'\n\nexport const SIGNED_UNCHANGED =\n 'The signed PDF is unchanged: the comments are kept beside it as markup.'\n\nexport interface MarkupDocument {\n external_id: string\n shared?: boolean | null\n current_version?: number | null\n versions?: VersionInfo[] | null\n}\n\nexport interface LegacyPrompt {\n count: number\n busy: boolean\n add: () => void\n discard: () => void\n}\n\nexport interface OlderMarkupNote {\n version: number\n busy: boolean\n /** The current version is a signed copy: say that copying leaves its signed PDF as it is. */\n signed: boolean\n copy: () => void\n}\n\nexport function useDocumentMarkup(\n documentData: MarkupDocument | null | undefined,\n /** The version on screen when it is an older one (a read-only snapshot). */\n snapshotVersion: number | undefined,\n /**\n * Whether the version on screen is a signed, sealed copy: locked, so no \"Download with markup\"\n * (and, for the current version, copied comments leave its signed PDF as it is).\n */\n currentSigned = false\n) {\n const { client, notify, saveFile, onDocumentsChanged } = useDocumentTools()\n const documentId = documentData?.external_id\n const currentVersion = documentData?.current_version ?? 1\n const shownVersion = snapshotVersion ?? currentVersion\n const versions = useMemo(() => documentData?.versions ?? [], [documentData?.versions])\n\n // Counts from this session's saves win over the (possibly stale) document record.\n const [localCounts, setLocalCounts] = useState<Record<string, number>>({})\n const countOf = useCallback(\n (n: number) =>\n localCounts[`${documentId}@${n}`] ?? versions.find((v) => v.n === n)?.markup_count ?? 0,\n [localCounts, documentId, versions]\n )\n const hasMarkup = countOf(shownVersion) > 0\n\n const [showOriginal, setShowOriginal] = useState(false)\n useEffect(() => setShowOriginal(false), [documentId, snapshotVersion])\n\n const refresh = useCallback(() => {\n if (!documentId || !onDocumentsChanged) return\n Promise.resolve(onDocumentsChanged([documentId], 'markup')).catch((e: unknown) =>\n console.warn('Could not refresh the document after a markup change', e)\n )\n }, [documentId, onDocumentsChanged])\n\n const onMarkupChange = useCallback(\n (snapshot: MarkupSnapshot) => {\n if (!documentId) return\n const key = `${documentId}@${shownVersion}`\n // The list's \"Download with markup\" and the version entries follow the first/last mark.\n if (countOf(shownVersion) > 0 !== snapshot.count > 0) refresh()\n setLocalCounts((counts) => ({ ...counts, [key]: snapshot.count }))\n },\n [documentId, shownVersion, countOf, refresh]\n )\n\n const downloadMarkup = useCallback(async () => {\n if (!documentId) return\n // A signed version is locked: its markup is never written into its PDF.\n if (currentSigned) {\n notify(SIGNED_LOCKED_REASON, 'info')\n return\n }\n try {\n const { blob, fileName } = await fetchMarkupPdf(\n client,\n documentId,\n snapshotVersion ? snapshotVersion : undefined\n )\n saveFile(blob, fileName)\n } catch (e) {\n notify(e instanceof Error ? e.message : 'The markup could not be downloaded', 'error')\n }\n }, [client, documentId, snapshotVersion, saveFile, notify, currentSigned])\n\n // --- Migration of this browser's layer (arbi:annotations:<docId>) ---\n const [legacyCount, setLegacyCount] = useState(0)\n const [migrating, setMigrating] = useState(false)\n const shared = documentData?.shared\n const loaded = !!documentData\n\n const migrate = useCallback(async () => {\n if (!documentId) return\n const layer = readLegacyLayer(documentId)\n if (!layer) return\n setMigrating(true)\n try {\n const added = await migrateLegacyLayer(documentId, layer, versions, currentVersion, client)\n setLegacyCount(0)\n setLocalCounts({})\n refresh()\n if (added > 0) {\n notify(\n `${added} annotation${added === 1 ? '' : 's'} from this browser saved to the document`,\n 'success',\n {\n description: shared\n ? 'They are now part of the shared markup.'\n : 'They are saved with the document, visible only to you.',\n }\n )\n }\n } catch (e) {\n notify(\n e instanceof Error ? e.message : 'The annotations from this browser could not be saved',\n 'error',\n { description: 'They are still kept in this browser; open the document again to retry.' }\n )\n } finally {\n setMigrating(false)\n }\n }, [client, documentId, versions, currentVersion, refresh, shared, notify])\n\n useEffect(() => {\n if (!documentId || !loaded) return\n const layer = readLegacyLayer(documentId)\n if (!layer) {\n setLegacyCount(0)\n return\n }\n if (layer.annotations.length === 0) {\n forgetLegacyLayer(documentId)\n setLegacyCount(0)\n return\n }\n // A private document is the user's own: its old layer simply becomes its markup. A shared one\n // would show the marks to everyone, so the user decides.\n if (shared) setLegacyCount(layer.annotations.length)\n else void migrate()\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [documentId, loaded, shared])\n\n const legacyPrompt: LegacyPrompt | null =\n legacyCount > 0 && !snapshotVersion\n ? {\n count: legacyCount,\n busy: migrating,\n add: () => void migrate(),\n discard: () => {\n if (documentId) forgetLegacyLayer(documentId)\n setLegacyCount(0)\n },\n }\n : null\n\n // --- Markup on an older version (a newer version starts with none) ---\n const [copying, setCopying] = useState(false)\n const olderWithMarkup = versionsWithMarkup(versions)\n .filter((v) => v.n !== currentVersion)\n .sort((a, b) => b.n - a.n)[0]\n const olderNote: OlderMarkupNote | null =\n !snapshotVersion && !hasMarkup && olderWithMarkup\n ? {\n version: olderWithMarkup.n,\n busy: copying,\n signed: currentSigned,\n copy: () => {\n if (!documentId) return\n setCopying(true)\n copyOpenThreads(documentId, olderWithMarkup.n, client)\n .then((n) => {\n if (n > 0) {\n setLocalCounts((c) => ({ ...c, [`${documentId}@${currentVersion}`]: n }))\n refresh()\n }\n notify(\n n > 0\n ? `${n} open comment thread${n === 1 ? '' : 's'} copied to version ${currentVersion}`\n : `Version ${olderWithMarkup.n} has no open comments`,\n n > 0 ? 'success' : 'info',\n // The markup is stored beside the version, so the sealed bytes do not change.\n n > 0 && currentSigned ? { description: SIGNED_UNCHANGED } : undefined\n )\n })\n .catch((e: unknown) =>\n notify(e instanceof Error ? e.message : 'The comments could not be copied', 'error')\n )\n .finally(() => setCopying(false))\n },\n }\n : null\n\n return {\n hasMarkup,\n showOriginal,\n setShowOriginal,\n onMarkupChange,\n downloadMarkup,\n legacyPrompt,\n olderNote,\n }\n}\n","/**\n * Saving a frozen copy: a SEPARATE document derived from the version it was frozen from\n * (`derived_from`, role `redaction` or `annotated`), never a new version of it. The original keeps\n * its place in every list and stays the current version; the copy sits beside it, in the same\n * folder and with the same workspace sharing.\n */\n\nimport type { DocumentToolsEnvironment, DocumentUploadQuery } from './environment'\n\nexport interface FrozenCopySource {\n /** The version on screen, which the copy is derived from. */\n documentId: string\n fileName: string | null | undefined\n shared: boolean\n folder?: string | null\n}\n\nconst baseName = (fileName: string | null | undefined) =>\n (fileName || 'document').replace(/\\.pdf$/i, '')\n\n/** \"Contract.pdf\" becomes \"Contract (redacted).pdf\"; a .txt or .docx keeps its extension inside. */\nexport function frozenCopyName(fileName: string | null | undefined, redacted: boolean): string {\n return `${baseName(fileName)} (${redacted ? 'redacted' : 'annotated'}).pdf`\n}\n\nexport function redactionLogName(fileName: string | null | undefined): string {\n return `${baseName(fileName)} (redaction log).csv`\n}\n\n/** Upload the frozen bytes as a new document derived from `source`; returns its id, if any. */\nexport async function uploadFrozenCopy(\n upload: NonNullable<DocumentToolsEnvironment['uploadDocument']>,\n bytes: Uint8Array,\n source: FrozenCopySource,\n redacted: boolean\n): Promise<string | undefined> {\n const file = new File([bytes as BlobPart], frozenCopyName(source.fileName, redacted), {\n type: 'application/pdf',\n })\n const query: DocumentUploadQuery = {\n derived_from: [source.documentId],\n derived_role: redacted ? 'redaction' : 'annotated',\n shared: source.shared,\n }\n if (source.folder) query.folder = source.folder\n const response = await upload({ file, query })\n return response?.doc_ext_ids?.[0]\n}\n","/**\n * Whether the document on screen can be annotated: only a PDF the viewer is actually showing.\n * Text and Word files are shown as a PDF too, so they qualify; images, audio, video, files that\n * cannot be previewed, drafts and streaming output do not, and neither does a read-only snapshot\n * or a comparison.\n */\n\nexport interface AnnotatableState {\n activeTab: string\n /** The PDF bytes have been fetched. */\n hasPdf: boolean\n isImage: boolean\n isVideo: boolean\n isAudio: boolean\n isDownloadOnly: boolean\n isDraft: boolean\n isStreaming: boolean\n isSnapshot: boolean\n isComparing: boolean\n}\n\nexport function canAnnotate(s: AnnotatableState): boolean {\n return (\n s.activeTab === 'pdf' &&\n s.hasPdf &&\n !s.isImage &&\n !s.isVideo &&\n !s.isAudio &&\n !s.isDownloadOnly &&\n !s.isDraft &&\n !s.isStreaming &&\n !s.isSnapshot &&\n !s.isComparing\n )\n}\n","/**\n * Reactive connectivity from React Query's `onlineManager` (the browser's online events, plus\n * whatever the host feeds it, e.g. a WebSocket). The markup autosave waits while it is false.\n */\n\nimport { useSyncExternalStore } from 'react'\nimport { onlineManager } from '@tanstack/react-query'\n\nexport function useIsOnline(): boolean {\n return useSyncExternalStore(\n (onChange) => onlineManager.subscribe(onChange),\n () => onlineManager.isOnline(),\n () => true\n )\n}\n","/**\n * Electronic signing. The backend (`src/core/esign.py` in ARBI) defines what a signature binds;\n * the helpers mirror the two pieces the browser must reproduce exactly: the statement of intent\n * shown to the signer, and the SHA-256 of the PDF the viewer displayed.\n */\n\nimport { generateUserKeypairs, signMessage, type components } from '@arbidocs/client'\nimport { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'\nimport { parseVersionRef } from '../artifacts/versions'\nimport { useDocumentTools, type DocumentToolsClient } from './environment'\n\n/**\n * Who signs: the name only. A role, a firm or a place go on the page as ordinary annotation text,\n * which is not part of the signature.\n */\nexport type SignerDetails = components['schemas']['SignerDetails']\n\n/** Same sentence as `esign.intent_text`; the dialog refuses to sign if the server's differs. */\nexport function intentText(signer: SignerDetails): string {\n return `I, ${signer.name.trim()}, sign this document electronically. I intend this electronic signature to have the same effect as my handwritten signature.`\n}\n\nexport async function sha256Hex(blob: Blob): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(await blob.arrayBuffer()))\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** A signature box drawn on the annotation overlay, as the signing API's placement. */\nexport function toAppearance(box: {\n page: number\n rect: { x: number; y: number; w: number; h: number }\n}): { page: number; x: number; y: number; width: number; height: number } {\n // The layer counts pages from 1, the signing API from 0. Both use fractions of the page as\n // displayed, origin top-left.\n return { page: box.page - 1, x: box.rect.x, y: box.rect.y, width: box.rect.w, height: box.rect.h }\n}\n\n/**\n * The smallest box the backend can draw a legible signature in: the signer's name and the\n * details line shrink to fit, so a box under these fractions of the page is shrunk to near\n * unreadable size. The backend's own default box is 0.40 x 0.10.\n */\nconst MIN_SIGNATURE_BOX = { width: 0.3, height: 0.07 }\n\nexport function isLegibleSignatureBox(rect: { w: number; h: number }): boolean {\n return rect.w >= MIN_SIGNATURE_BOX.width && rect.h >= MIN_SIGNATURE_BOX.height\n}\n\n// ── Signing through the API ─────────────────────────────────────────────────────────────────\n\nexport type SignatureAppearance = components['schemas']['SignatureAppearance']\nexport type SignatureStatusResponse = components['schemas']['SignatureStatusResponse']\nexport type SignatureRecord = components['schemas']['SignatureRecord']\nexport type SignDocumentResponse = components['schemas']['SignDocumentResponse']\n\nconst SIGNATURES_PATH = '/v1/document/{document_ext_id}/signatures'\n/**\n * The same key openapi-react-query gives this request (`['get', path, init]`), so a host that\n * reads or persists the API cache by path treats it like its own queries.\n */\nconst SIGNATURES_KEY = ['get', SIGNATURES_PATH] as const\n\nfunction errorDetail(error: unknown, fallback: string): string {\n const detail = (error as { detail?: unknown } | undefined)?.detail\n return typeof detail === 'string' ? detail : fallback\n}\n\n/** Whether a document version is a signed copy, and its signatures. */\nexport async function fetchDocumentSignatures(\n client: DocumentToolsClient,\n documentRef: string\n): Promise<SignatureStatusResponse> {\n const { docId, version } = parseVersionRef(documentRef)\n const { data, error } = await client.GET(SIGNATURES_PATH, {\n params: { path: { document_ext_id: docId }, ...(version ? { query: { version } } : {}) },\n })\n if (!data) throw new Error(errorDetail(error, 'The signatures could not be read'))\n return data\n}\n\n/**\n * Is a document version a signed copy? `documentId` is a document id (its current version) or a\n * version reference `doc-…@v{n}`. Needs a React Query `QueryClientProvider`.\n */\nexport function useDocumentSignatures(documentId: string | null | undefined, enabled = true) {\n const { client } = useDocumentTools()\n const { docId, version } = parseVersionRef(documentId)\n return useQuery({\n queryKey: [\n ...SIGNATURES_KEY,\n { params: { path: { document_ext_id: docId }, ...(version ? { query: { version } } : {}) } },\n ],\n queryFn: () => fetchDocumentSignatures(client, documentId!),\n enabled: enabled && !!docId,\n staleTime: 60_000,\n })\n}\n\n/**\n * Why the server would not sign: the PDF of a Word or text document is still being rendered\n * (`preparing`, worth another try in a moment), or the version on screen is no longer the current\n * one (`stale`: only the current version can be signed, so the signer reopens it).\n */\nexport type SigningErrorReason = 'preparing' | 'stale' | 'failed'\n\nexport class SigningError extends Error {\n readonly reason: SigningErrorReason\n constructor(message: string, reason: SigningErrorReason) {\n super(message)\n this.name = 'SigningError'\n this.reason = reason\n }\n}\n\n/** The 409s the backend's signing router raises, told apart by their wording. */\nfunction signingErrorReason(detail: string): SigningErrorReason {\n if (/still being prepared/i.test(detail)) return 'preparing'\n if (/no longer the current version/i.test(detail)) return 'stale'\n return 'failed'\n}\n\nfunction signingError(error: unknown, fallback: string): SigningError {\n const detail = errorDetail(error, fallback)\n return new SigningError(detail, signingErrorReason(detail))\n}\n\n/** How often, and how long apart, a prepare is retried while the PDF is still being rendered. */\nexport const PREPARE_RETRIES = 3\nexport const PREPARE_RETRY_DELAY_MS = 1500\n\nconst wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport interface SignDocumentVars {\n documentId: string\n /**\n * The PDF bytes the viewer is showing (`GET /view?version=`, never the original's download): the\n * signer signs exactly these.\n */\n pdfBlob: Blob\n /**\n * The version `pdfBlob` is of. The server signs only the current version and refuses\n * (`SigningError` `stale`) when this one has been superseded. Omitted = the current version.\n */\n version?: number\n email: string\n password: string\n signer: SignerDetails\n /** Where the signature goes; omitted = the backend default (bottom of the last page). */\n appearance?: SignatureAppearance\n /** Draw the signing date under the signature. Default off: only the signature is drawn. */\n includeDate?: boolean\n}\n\n/**\n * Sign a document: the server prepares the statement, the browser checks that it covers the PDF\n * on screen under the wording the signer read, re-derives the user's Ed25519 key from their\n * password and signs it, and the server seals the signed copy as a new version.\n *\n * What is drawn on the page is only the signature (the signer's name as the signature mark) and,\n * with `includeDate`, the date; anyone can click it to open its certificate. A role, a firm or a\n * place go on the page as ordinary annotation text, which is not part of the signature.\n */\nexport async function signDocument(\n client: DocumentToolsClient,\n deploymentDomain: string,\n {\n documentId,\n pdfBlob,\n email,\n password,\n signer,\n appearance,\n includeDate = false,\n version,\n }: SignDocumentVars\n): Promise<SignDocumentResponse> {\n const path = { document_ext_id: documentId }\n // One body for both calls: the server refuses a /sign whose include_date (or placement) differs\n // from what was prepared, since what the signature shows is part of what is signed.\n const body = {\n signer: { name: signer.name },\n ...(appearance ? { appearance } : {}),\n include_date: includeDate,\n ...(version ? { version } : {}),\n }\n\n // A Word or text document's PDF is rendered after upload: while it is, prepare says so, and a\n // short wait usually sees it ready.\n const prepare = () =>\n client.POST('/v1/document/{document_ext_id}/sign/prepare', { params: { path }, body })\n let prepared = await prepare()\n for (let attempt = 0; !prepared.data && attempt < PREPARE_RETRIES; attempt++) {\n if (signingError(prepared.error, '').reason !== 'preparing') break\n await wait(PREPARE_RETRY_DELAY_MS)\n prepared = await prepare()\n }\n if (!prepared.data) throw signingError(prepared.error, 'Could not prepare signing')\n const { statement, intent, source_sha256, timestamp } = prepared.data\n // Sign only what was on screen, under the wording the signer read.\n if ((await sha256Hex(pdfBlob)) !== source_sha256) {\n throw new Error('The document changed since it was opened. Reopen it and sign again.')\n }\n if (intent !== intentText(signer)) throw new Error('Signing statement mismatch; not signed.')\n\n const { signingKeyPair } = await generateUserKeypairs(email, password, deploymentDomain)\n const signed = await client.POST('/v1/document/{document_ext_id}/sign', {\n params: { path },\n body: { ...body, timestamp, signature: signMessage(statement, signingKeyPair.secretKey) },\n })\n if (!signed.data) throw signingError(signed.error, 'Signing failed')\n return signed.data\n}\n\n/** The signing mutation. On success the host hears the document changed (`'signed'`). */\nexport function useSignDocument() {\n const env = useDocumentTools()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (vars: SignDocumentVars) => {\n if (!env.deploymentDomain) throw new Error('Signing is not set up: no deployment domain')\n return signDocument(env.client, env.deploymentDomain, vars)\n },\n onSuccess: async (result) => {\n // The signed copy is the document's new current version: the host refreshes its row,\n // versions and rendered PDF, and the signature badge reads again.\n await env.onDocumentsChanged?.([result.doc_ext_id], 'signed')\n await queryClient.invalidateQueries({ queryKey: SIGNATURES_KEY })\n },\n })\n}\n","/**\n * Checking a signature from its reference, without signing in: the public certificate behind the\n * link on a signed PDF's signature (`GET /v1/sign/verify/{reference}`). It names who signed and\n * when, says whether the signed document is unchanged since, and carries the SHA-256 of the signed\n * PDF and of each signed revision, so anyone can check their own copy in the browser (the file is\n * never uploaded). No email addresses and no document content.\n */\n\nimport type { components } from '@arbidocs/client'\nimport { useQuery } from '@tanstack/react-query'\nimport { useDocumentTools, type DocumentToolsClient } from './environment'\nimport { sha256Hex } from './signing'\n\nexport const VERIFY_PATH = '/v1/sign/verify/{reference}'\n\nexport type SignatureVerification = components['schemas']['SignatureVerification']\nexport type VerifiedSignature = components['schemas']['VerifiedSignature']\n\n/** A signature reference as the backend issues them: `sig-` and 128 random bits in hex. */\nconst REFERENCE = /^sig-[0-9a-f]{32}$/\n\nexport function isSignatureReference(reference: string | null | undefined): boolean {\n return !!reference && REFERENCE.test(reference)\n}\n\nexport class SignatureVerificationError extends Error {\n constructor(\n message: string,\n readonly status?: number\n ) {\n super(message)\n this.name = 'SignatureVerificationError'\n }\n}\n\nconst VERIFY_ERRORS: Record<number, string> = {\n 404: 'No signature has this reference.',\n 429: 'Too many checks, try again in a minute.',\n}\n\nexport async function fetchSignatureVerification(\n client: DocumentToolsClient,\n reference: string\n): Promise<SignatureVerification> {\n if (!isSignatureReference(reference)) {\n throw new SignatureVerificationError('This is not a signature reference.')\n }\n const { data, response } = await client.GET(VERIFY_PATH, {\n params: { path: { reference } },\n })\n if (!response.ok || !data) {\n throw new SignatureVerificationError(\n VERIFY_ERRORS[response.status] ?? 'The signature could not be checked right now.',\n response.status\n )\n }\n return data\n}\n\n/** The certificate of a signature reference. Needs a `<DocumentToolsProvider>` (no user). */\nexport function useSignatureVerification(reference: string | null | undefined) {\n const { client } = useDocumentTools()\n return useQuery({\n queryKey: ['get', VERIFY_PATH, { params: { path: { reference } } }],\n queryFn: () => fetchSignatureVerification(client, reference!),\n enabled: !!reference,\n retry: false,\n })\n}\n\n/**\n * What a copy is: the signed document as it stands (`current`), the document as it was when an\n * earlier signer signed it (`earlier`, a counter-signed PDF's earlier revision), or neither.\n */\nexport type CopyMatch =\n { kind: 'current' } | { kind: 'earlier'; signature: VerifiedSignature } | { kind: 'none' }\n\n/** Compare a file with the signed PDF and its signed revisions. Hashed here; nothing is uploaded. */\nexport async function matchSignedCopy(\n file: Blob,\n verification: Pick<SignatureVerification, 'document_sha256' | 'signatures'>\n): Promise<CopyMatch> {\n const hash = await sha256Hex(file)\n if (hash === verification.document_sha256.toLowerCase()) return { kind: 'current' }\n const signature = verification.signatures.find((s) => s.sha256.toLowerCase() === hash)\n return signature ? { kind: 'earlier', signature } : { kind: 'none' }\n}\n"]}