@embedpdf/plugin-attachment 3.0.0-next.22 → 3.0.0-next.23

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.
@@ -6,8 +6,8 @@ const AttachmentToken = createCapabilityToken("attachment", {
6
6
  promises: {
7
7
  ensureLoaded: true,
8
8
  refresh: true,
9
- add: true,
10
- remove: true,
9
+ create: true,
10
+ delete: true,
11
11
  download: true
12
12
  }
13
13
  });
@@ -29,4 +29,4 @@ function displayNameOf(file) {
29
29
  //#endregion
30
30
  export { AttachmentToken as n, displayNameOf as t };
31
31
 
32
- //# sourceMappingURL=contract-CqFkPaxs.js.map
32
+ //# sourceMappingURL=contract-Bz7NXE3o.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-Bz7NXE3o.js","names":[],"sources":["../src/token.ts","../src/names.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { AttachmentCapability } from './contract';\n\nexport const AttachmentToken = createCapabilityToken<AttachmentCapability>('attachment', {\n hint: \"add attachmentPlugin() from '@embedpdf/plugin-attachment' to your plugins list\",\n // Without a document, an adapter's stand-in rejects these with `not-ready`, as the\n // capability would; the type asks for every member that returns a promise.\n promises: {\n ensureLoaded: true,\n refresh: true,\n create: true,\n delete: true,\n download: true,\n },\n});\n","/**\n * Control characters, and the bidi controls a name can use to look like\n * another: with a right-to-left override (U+202E) where `[RLO]` stands,\n * `invoice[RLO]fdp.exe` shows as `invoiceexe.pdf`.\n */\n// eslint-disable-next-line no-control-regex -- finding control characters is its job\nconst HIDDEN = /[\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g;\n\n/**\n * A file's name as a person may see it and save it: without control\n * characters and bidi controls, trimmed. `attachment` when nothing is left.\n */\nexport function displayNameOf(file: { readonly name: string }): string {\n return file.name.replace(HIDDEN, '').trim() || 'attachment';\n}\n"],"mappings":";;;AAKA,MAAa,kBAAkB,sBAA4C,cAAc;CACvF,MAAM;CAGN,UAAU;EACR,cAAc;EACd,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,UAAU;CACZ;AACF,CAAC;;;;;;;;ACVD,MAAM,SAAS;;;;;AAMf,SAAgB,cAAc,MAAyC;CACrE,OAAO,KAAK,KAAK,QAAQ,QAAQ,EAAE,CAAC,CAAC,KAAK,KAAK;AACjD"}
@@ -5,8 +5,8 @@ const AttachmentToken = (0, require("@embedpdf/core").createCapabilityToken)("at
5
5
  promises: {
6
6
  ensureLoaded: true,
7
7
  refresh: true,
8
- add: true,
9
- remove: true,
8
+ create: true,
9
+ delete: true,
10
10
  download: true
11
11
  }
12
12
  });
@@ -39,4 +39,4 @@ Object.defineProperty(exports, "displayNameOf", {
39
39
  }
40
40
  });
41
41
 
42
- //# sourceMappingURL=contract-C__XpO5g.cjs.map
42
+ //# sourceMappingURL=contract-Cxnx21qM.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-Cxnx21qM.cjs","names":[],"sources":["../src/token.ts","../src/names.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { AttachmentCapability } from './contract';\n\nexport const AttachmentToken = createCapabilityToken<AttachmentCapability>('attachment', {\n hint: \"add attachmentPlugin() from '@embedpdf/plugin-attachment' to your plugins list\",\n // Without a document, an adapter's stand-in rejects these with `not-ready`, as the\n // capability would; the type asks for every member that returns a promise.\n promises: {\n ensureLoaded: true,\n refresh: true,\n create: true,\n delete: true,\n download: true,\n },\n});\n","/**\n * Control characters, and the bidi controls a name can use to look like\n * another: with a right-to-left override (U+202E) where `[RLO]` stands,\n * `invoice[RLO]fdp.exe` shows as `invoiceexe.pdf`.\n */\n// eslint-disable-next-line no-control-regex -- finding control characters is its job\nconst HIDDEN = /[\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g;\n\n/**\n * A file's name as a person may see it and save it: without control\n * characters and bidi controls, trimmed. `attachment` when nothing is left.\n */\nexport function displayNameOf(file: { readonly name: string }): string {\n return file.name.replace(HIDDEN, '').trim() || 'attachment';\n}\n"],"mappings":";;AAKA,MAAa,mBAAA,2BAAA,CAAA,CAAA,sBAAA,CAA8D,cAAc;CACvF,MAAM;CAGN,UAAU;EACR,cAAc;EACd,SAAS;EACT,QAAQ;EACR,QAAQ;EACR,UAAU;CACZ;AACF,CAAC;;;;;;;;ACVD,MAAM,SAAS;;;;;AAMf,SAAgB,cAAc,MAAyC;CACrE,OAAO,KAAK,KAAK,QAAQ,QAAQ,EAAE,CAAC,CAAC,KAAK,KAAK;AACjD"}
@@ -38,7 +38,7 @@ interface AttachedFile extends Readonly<AttachmentFileInfo> {
38
38
  */
39
39
  interface AttachmentsChangedEvent {
40
40
  /** `restored`: an undo brought a removed file back. */
41
- readonly type: 'added' | 'removed' | 'restored';
41
+ readonly type: 'created' | 'deleted' | 'restored';
42
42
  /** The files it touched; for a removal, as they were. */
43
43
  readonly files: readonly AttachedFile[];
44
44
  readonly origin: EventOrigin;
@@ -82,9 +82,9 @@ interface AttachmentCapability {
82
82
  /** Whether this session may take files out (`doc.download`): `download()`. */
83
83
  canDownload(): boolean;
84
84
  /** Whether this session may add and remove attachments (`doc.attachments.modify`). */
85
- canAdd(): boolean;
86
- /** Whether this session may remove this file: `canAdd()` for an attachment, the annotation plugin's `canDelete()` for a page's file. */
87
- canRemove(file: AttachedFile): boolean;
85
+ canCreate(): boolean;
86
+ /** Whether this session may remove this file: `canCreate()` for an attachment, the annotation plugin's `canDelete()` for a page's file. */
87
+ canDelete(file: AttachedFile): boolean;
88
88
  /**
89
89
  * Attach files to the document, as one change: one step of the history.
90
90
  * A `File` brings its name and type; bytes need a `name`. A name the
@@ -94,7 +94,7 @@ interface AttachmentCapability {
94
94
  * `invalid-input` for bytes without a name, `operation-cancelled` or
95
95
  * `instance-closed`.
96
96
  */
97
- add(files: readonly AttachmentFileSource[], options?: OperationOptions): Promise<readonly AttachedFile[]>;
97
+ create(files: readonly AttachmentFileSource[], options?: OperationOptions): Promise<readonly AttachedFile[]>;
98
98
  /**
99
99
  * Remove a file, as one step of the history: an attachment, or a page's
100
100
  * file attachment annotation (through the annotation plugin). It goes at
@@ -102,7 +102,7 @@ interface AttachmentCapability {
102
102
  * for a file the document doesn't have, `operation-cancelled` or
103
103
  * `instance-closed`.
104
104
  */
105
- remove(file: AttachedFile, options?: OperationOptions): Promise<void>;
105
+ delete(file: AttachedFile, options?: OperationOptions): Promise<void>;
106
106
  /**
107
107
  * The file's bytes, ready to save: its name cleaned (`displayNameOf`) and
108
108
  * its type. A pending add is waited for. Rejects `permission-denied`
@@ -120,4 +120,4 @@ interface AttachmentCapability {
120
120
  }
121
121
  //#endregion
122
122
  export { AttachmentContent as a, AttachmentRef as c, displayNameOf as d, AttachmentToken as f, AttachmentCapability as i, AttachmentsChangedEvent as l, AttachedFile as n, AttachmentFileInfo as o, AttachedFileHome as r, AttachmentFileSource as s, AnnotationRef as t, AttachmentsResyncedEvent as u };
123
- //# sourceMappingURL=contract-D2t_jdnb.d.ts.map
123
+ //# sourceMappingURL=contract-G9XK_m9w.d.cts.map
@@ -38,7 +38,7 @@ interface AttachedFile extends Readonly<AttachmentFileInfo> {
38
38
  */
39
39
  interface AttachmentsChangedEvent {
40
40
  /** `restored`: an undo brought a removed file back. */
41
- readonly type: 'added' | 'removed' | 'restored';
41
+ readonly type: 'created' | 'deleted' | 'restored';
42
42
  /** The files it touched; for a removal, as they were. */
43
43
  readonly files: readonly AttachedFile[];
44
44
  readonly origin: EventOrigin;
@@ -82,9 +82,9 @@ interface AttachmentCapability {
82
82
  /** Whether this session may take files out (`doc.download`): `download()`. */
83
83
  canDownload(): boolean;
84
84
  /** Whether this session may add and remove attachments (`doc.attachments.modify`). */
85
- canAdd(): boolean;
86
- /** Whether this session may remove this file: `canAdd()` for an attachment, the annotation plugin's `canDelete()` for a page's file. */
87
- canRemove(file: AttachedFile): boolean;
85
+ canCreate(): boolean;
86
+ /** Whether this session may remove this file: `canCreate()` for an attachment, the annotation plugin's `canDelete()` for a page's file. */
87
+ canDelete(file: AttachedFile): boolean;
88
88
  /**
89
89
  * Attach files to the document, as one change: one step of the history.
90
90
  * A `File` brings its name and type; bytes need a `name`. A name the
@@ -94,7 +94,7 @@ interface AttachmentCapability {
94
94
  * `invalid-input` for bytes without a name, `operation-cancelled` or
95
95
  * `instance-closed`.
96
96
  */
97
- add(files: readonly AttachmentFileSource[], options?: OperationOptions): Promise<readonly AttachedFile[]>;
97
+ create(files: readonly AttachmentFileSource[], options?: OperationOptions): Promise<readonly AttachedFile[]>;
98
98
  /**
99
99
  * Remove a file, as one step of the history: an attachment, or a page's
100
100
  * file attachment annotation (through the annotation plugin). It goes at
@@ -102,7 +102,7 @@ interface AttachmentCapability {
102
102
  * for a file the document doesn't have, `operation-cancelled` or
103
103
  * `instance-closed`.
104
104
  */
105
- remove(file: AttachedFile, options?: OperationOptions): Promise<void>;
105
+ delete(file: AttachedFile, options?: OperationOptions): Promise<void>;
106
106
  /**
107
107
  * The file's bytes, ready to save: its name cleaned (`displayNameOf`) and
108
108
  * its type. A pending add is waited for. Rejects `permission-denied`
@@ -120,4 +120,4 @@ interface AttachmentCapability {
120
120
  }
121
121
  //#endregion
122
122
  export { AttachmentContent as a, AttachmentRef as c, displayNameOf as d, AttachmentToken as f, AttachmentCapability as i, AttachmentsChangedEvent as l, AttachedFile as n, AttachmentFileInfo as o, AttachedFileHome as r, AttachmentFileSource as s, AnnotationRef as t, AttachmentsResyncedEvent as u };
123
- //# sourceMappingURL=contract-D2t_jdnb.d.cts.map
123
+ //# sourceMappingURL=contract-G9XK_m9w.d.ts.map
package/dist/contract.cjs CHANGED
@@ -1,4 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_contract = require("./contract-C__XpO5g.cjs");
2
+ const require_contract = require("./contract-Cxnx21qM.cjs");
3
3
  exports.AttachmentToken = require_contract.AttachmentToken;
4
4
  exports.displayNameOf = require_contract.displayNameOf;
@@ -1,2 +1,2 @@
1
- import { a as AttachmentContent, c as AttachmentRef, d as displayNameOf, f as AttachmentToken, i as AttachmentCapability, l as AttachmentsChangedEvent, n as AttachedFile, o as AttachmentFileInfo, r as AttachedFileHome, s as AttachmentFileSource, t as AnnotationRef, u as AttachmentsResyncedEvent } from "./contract-D2t_jdnb.cjs";
1
+ import { a as AttachmentContent, c as AttachmentRef, d as displayNameOf, f as AttachmentToken, i as AttachmentCapability, l as AttachmentsChangedEvent, n as AttachedFile, o as AttachmentFileInfo, r as AttachedFileHome, s as AttachmentFileSource, t as AnnotationRef, u as AttachmentsResyncedEvent } from "./contract-G9XK_m9w.cjs";
2
2
  export { type AnnotationRef, AttachedFile, AttachedFileHome, AttachmentCapability, type AttachmentContent, type AttachmentFileInfo, type AttachmentFileSource, type AttachmentRef, AttachmentToken, AttachmentsChangedEvent, AttachmentsResyncedEvent, displayNameOf };
@@ -1,2 +1,2 @@
1
- import { a as AttachmentContent, c as AttachmentRef, d as displayNameOf, f as AttachmentToken, i as AttachmentCapability, l as AttachmentsChangedEvent, n as AttachedFile, o as AttachmentFileInfo, r as AttachedFileHome, s as AttachmentFileSource, t as AnnotationRef, u as AttachmentsResyncedEvent } from "./contract-D2t_jdnb.js";
1
+ import { a as AttachmentContent, c as AttachmentRef, d as displayNameOf, f as AttachmentToken, i as AttachmentCapability, l as AttachmentsChangedEvent, n as AttachedFile, o as AttachmentFileInfo, r as AttachedFileHome, s as AttachmentFileSource, t as AnnotationRef, u as AttachmentsResyncedEvent } from "./contract-G9XK_m9w.js";
2
2
  export { type AnnotationRef, AttachedFile, AttachedFileHome, AttachmentCapability, type AttachmentContent, type AttachmentFileInfo, type AttachmentFileSource, type AttachmentRef, AttachmentToken, AttachmentsChangedEvent, AttachmentsResyncedEvent, displayNameOf };
package/dist/contract.js CHANGED
@@ -1,2 +1,2 @@
1
- import { n as AttachmentToken, t as displayNameOf } from "./contract-CqFkPaxs.js";
1
+ import { n as AttachmentToken, t as displayNameOf } from "./contract-Bz7NXE3o.js";
2
2
  export { AttachmentToken, displayNameOf };
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_contract = require("./contract-C__XpO5g.cjs");
2
+ const require_contract = require("./contract-Cxnx21qM.cjs");
3
3
  let _embedpdf_core = require("@embedpdf/core");
4
4
  let _embedpdf_plugin_annotation_contract = require("@embedpdf/plugin-annotation/contract");
5
5
  let _embedpdf_plugin_stage_contract = require("@embedpdf/plugin-stage/contract");
@@ -109,8 +109,8 @@ function predictedFile(op) {
109
109
  name: op.file.name,
110
110
  mimeType: op.file.mimeType ?? null,
111
111
  description: op.file.description ?? null,
112
- size: bytes === void 0 ? null : bytes instanceof Uint8Array ? bytes.byteLength : bytes.size,
113
- checksum: null,
112
+ sizeBytes: bytes === void 0 ? null : bytes instanceof Uint8Array ? bytes.byteLength : bytes.size,
113
+ md5: null,
114
114
  createdAt: null,
115
115
  modifiedAt: null
116
116
  };
@@ -194,7 +194,7 @@ function createAttachmentController(ctx) {
194
194
  const factOf = (event, previous) => {
195
195
  switch (event.type) {
196
196
  case "attachments.created": return {
197
- type: "added",
197
+ type: "created",
198
198
  files: [fileOfAttachment(event.attachment)]
199
199
  };
200
200
  case "attachments.restored": return {
@@ -204,7 +204,7 @@ function createAttachmentController(ctx) {
204
204
  case "attachments.deleted": {
205
205
  const gone = previous?.find((file) => file.ref.key === event.deleted?.key);
206
206
  return {
207
- type: "removed",
207
+ type: "deleted",
208
208
  files: gone ? [fileOfAttachment(gone)] : []
209
209
  };
210
210
  }
@@ -218,7 +218,7 @@ function createAttachmentController(ctx) {
218
218
  load: async (doc) => ({ value: (await doc.attachments.list()).attachments }),
219
219
  fold: foldFiles,
220
220
  predict: predictFiles,
221
- changed: ({ cause, event, previous, next }) => {
221
+ onChanged: ({ cause, event, previous, next }) => {
222
222
  if (!next) return;
223
223
  if (cause === "load") {
224
224
  resynced.emit({ files: next.map(fileOfAttachment) });
@@ -292,7 +292,7 @@ function createAttachmentController(ctx) {
292
292
  resources: { file: data instanceof ArrayBuffer ? new Uint8Array(data) : data }
293
293
  };
294
294
  };
295
- const add = async (sources, options) => {
295
+ const create = async (sources, options) => {
296
296
  refuse(MODIFY, "attachment.add", options);
297
297
  if (sources.length === 0) return NO_FILES;
298
298
  await ctx.cancellable(options?.signal, files.ensureLoaded());
@@ -345,10 +345,10 @@ function createAttachmentController(ctx) {
345
345
  const annotation = annotations();
346
346
  const record = annotation?.get(file.home.ref);
347
347
  if (!annotation || !record) return;
348
- annotation.selection.set([record.ref]);
348
+ annotation.selection.select([record.ref]);
349
349
  ctx.tryGet(_embedpdf_plugin_stage_contract.StageToken)?.reveal(record.ref.page, {
350
350
  rect: record.rect,
351
- anchor: {
351
+ align: {
352
352
  x: "center",
353
353
  y: .35
354
354
  },
@@ -365,10 +365,10 @@ function createAttachmentController(ctx) {
365
365
  ensureLoaded: (options) => ctx.cancellable(options?.signal, files.ensureLoaded()),
366
366
  refresh: (options) => ctx.cancellable(options?.signal, files.refresh()),
367
367
  canDownload: () => ctx.allows(DOWNLOAD),
368
- canAdd: () => ctx.allows(MODIFY),
369
- canRemove: (file) => file.home.kind === "page" ? annotations()?.canDelete(file.home.ref) ?? false : ctx.allows(MODIFY),
370
- add,
371
- remove,
368
+ canCreate: () => ctx.allows(MODIFY),
369
+ canDelete: (file) => file.home.kind === "page" ? annotations()?.canDelete(file.home.ref) ?? false : ctx.allows(MODIFY),
370
+ create,
371
+ delete: remove,
372
372
  download,
373
373
  reveal,
374
374
  onChanged: changed.on,
@@ -403,14 +403,14 @@ const attachmentState = (0, _embedpdf_core.defineState)(require_contract.Attachm
403
403
  files: attachment.list(),
404
404
  selected: attachment.getSelected(),
405
405
  status: attachment.getStatus(),
406
- canAdd: attachment.canAdd(),
406
+ canCreate: attachment.canCreate(),
407
407
  canDownload: attachment.canDownload()
408
408
  }),
409
409
  empty: {
410
410
  files: [],
411
411
  selected: [],
412
412
  status: "idle",
413
- canAdd: false,
413
+ canCreate: false,
414
414
  canDownload: false
415
415
  },
416
416
  ensure: (attachment) => attachment.ensureLoaded()
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["AnnotationToken","PluginError","displayNameOf","StageToken","AttachmentToken","AnnotationToken","StageToken","AttachmentToken"],"sources":["../src/model.ts","../src/sync/files.ts","../src/controller.ts","../src/attachment.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The attachment model: the document's attachments as the mirror holds\n * them, how an attachment and a page's file become one `AttachedFile`, and\n * the name a new file takes. Pure.\n */\nimport {\n annotationKey,\n type Annotation,\n type AnnotationRef,\n type Attachment,\n type AttachmentRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { AttachedFile } from './contract';\n\n/** The session's part: the selected files, by id, in the order they were selected. */\nexport interface AttachmentModel {\n readonly selected: readonly string[];\n}\n\nexport const initialAttachmentModel = (): AttachmentModel => ({ selected: [] });\n\n/** Make these files the selection; the same ids leave the state as it is. */\nexport function selected(state: AttachmentModel, ids: readonly string[]): AttachmentModel {\n const unique = ids.filter((id, i) => ids.indexOf(id) === i);\n const same =\n unique.length === state.selected.length && unique.every((id, i) => id === state.selected[i]);\n return same ? state : { ...state, selected: unique };\n}\n\n/** The document's attachments, in the order its name tree keeps them; `null` before the first read lands. */\nexport type DocumentFiles = readonly Attachment[] | null;\n\n/** An attachment's id: its key. */\nexport const documentFileId = (ref: AttachmentRef): string => `doc:${ref.key}`;\n\n/** A page file's id: its annotation's key. */\nexport const pageFileId = (ref: AnnotationRef): string => `page:${annotationKey(ref)}`;\n\n/** An attachment as the list shows it. */\nexport function documentFileOf(attachment: Attachment): AttachedFile {\n const { ref, index: _index, ...info } = attachment;\n return { ...info, id: documentFileId(ref), home: { kind: 'document', ref } };\n}\n\n/** A file attachment annotation's file as the list shows it; `null` for another kind, or one without a file. */\nexport function pageFileOf(annotation: Annotation): AttachedFile | null {\n if (annotation.subtype !== 'file-attachment' || !annotation.file) return null;\n return {\n ...annotation.file,\n id: pageFileId(annotation.ref),\n home: { kind: 'page', ref: annotation.ref },\n };\n}\n\n/**\n * `name`, or, when a file has it already, the name with the first number\n * that makes it free: `notes (2).txt`, then `notes (3).txt`. The number goes\n * before the extension, as a file manager puts it.\n */\nexport function freeName(name: string, taken: ReadonlySet<string>): string {\n if (!taken.has(name)) return name;\n const dot = name.lastIndexOf('.');\n const stem = dot > 0 ? name.slice(0, dot) : name;\n const extension = dot > 0 ? name.slice(dot) : '';\n for (let number = 2; ; number++) {\n const candidate = `${stem} (${number})${extension}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n","/**\n * How the document's attachments change: `foldFiles` applies one confirmed\n * event, the mirror's `fold`; `predictFiles` applies one op of a pending\n * change by the engine's rules, the mirror's `predict`; `undoOf` says what\n * undoing ops looks like. Pure.\n */\nimport type { PredictedOp } from '@embedpdf/core';\nimport {\n toAttachmentRef,\n type Attachment,\n type ChangeOp,\n type DocumentEvent,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { DocumentFiles } from '../model';\n\ntype CreateOp = Extract<ChangeOp, { type: 'attachments.create' }>;\n\n/** The files with each `index` its position, keeping the files whose position held. */\nfunction indexed(files: readonly Attachment[]): readonly Attachment[] {\n return files.map((file, index) => (file.index === index ? file : { ...file, index }));\n}\n\nconst has = (files: readonly Attachment[], key: string): boolean =>\n files.some((file) => file.ref.key === key);\n\n/**\n * The files with `attachment` among them, before the first key that sorts\n * after its own, as the name tree puts a new entry; one with its key gives\n * way to it.\n */\nfunction withFile(files: readonly Attachment[], attachment: Attachment): readonly Attachment[] {\n const key = attachment.ref.key;\n const rest = files.filter((file) => file.ref.key !== key);\n const at = rest.findIndex((file) => file.ref.key > key);\n return indexed(\n at < 0 ? [...rest, attachment] : [...rest.slice(0, at), attachment, ...rest.slice(at)],\n );\n}\n\nfunction withoutFile(files: readonly Attachment[], key: string): readonly Attachment[] {\n return has(files, key) ? indexed(files.filter((file) => file.ref.key !== key)) : files;\n}\n\n/* ── confirmed events ────────────────────────────────────────────────────── */\n\n/** One confirmed event, applied with the record it carries. Before the first load there is nothing to apply it to. */\nexport function foldFiles(files: DocumentFiles, event: DocumentEvent): DocumentFiles {\n if (!files) return files;\n switch (event.type) {\n case 'attachments.created':\n case 'attachments.restored':\n return withFile(files, event.attachment);\n case 'attachments.deleted':\n return event.deleted ? withoutFile(files, event.deleted.key) : files;\n default:\n return files;\n }\n}\n\n/* ── pending changes ─────────────────────────────────────────────────────── */\n\n/** A file a create adds, as it shows until the engine answers: what the op says of it, and its size. */\nfunction predictedFile(op: CreateOp): Attachment {\n const bytes = op.resources.file;\n return {\n ref: toAttachmentRef(op.file.name),\n index: 0,\n name: op.file.name,\n mimeType: op.file.mimeType ?? null,\n description: op.file.description ?? null,\n size: bytes === undefined ? null : bytes instanceof Uint8Array ? bytes.byteLength : bytes.size,\n checksum: null,\n createdAt: null,\n modifiedAt: null,\n };\n}\n\n/**\n * One op of a change this session staged, shown before the engine answers,\n * by the engine's rules: a create of a name a file has, a delete of a file\n * that isn't there, and a restore of a name a file has change nothing.\n */\nexport function predictFiles(files: DocumentFiles, op: PredictedOp): DocumentFiles {\n if (!files) return files;\n switch (op.type) {\n case 'attachments.create':\n return has(files, op.file.name) ? files : withFile(files, predictedFile(op));\n case 'attachments.delete':\n return withoutFile(files, op.ref.key);\n case 'attachments.restore':\n return has(files, op.attachment.ref.key) ? files : withFile(files, op.attachment);\n default:\n return files;\n }\n}\n\n/** What undoing one op looks like, read off the files it applies to. */\nfunction undoOfOp(files: readonly Attachment[], op: ChangeOp): PredictedOp[] {\n switch (op.type) {\n case 'attachments.create':\n return [{ type: 'attachments.delete', ref: toAttachmentRef(op.file.name) }];\n case 'attachments.delete': {\n const attachment = files.find((file) => file.ref.key === op.ref.key);\n return attachment ? [{ type: 'attachments.restore', attachment }] : [];\n }\n default:\n return [];\n }\n}\n\n/**\n * What undoing `ops` looks like, read off the files they apply to, each op\n * on the files the ops before it leave; the last op is undone first.\n */\nexport function undoOf(files: DocumentFiles, ops: readonly ChangeOp[]): PredictedOp[] {\n if (!files) return [];\n const undo: PredictedOp[][] = [];\n let current = files;\n for (const op of ops) {\n undo.push(undoOfOp(current, op));\n current = predictFiles(current, op) ?? current;\n }\n return undo.reverse().flat();\n}\n","import {\n memo,\n PluginError,\n toPluginError,\n type DocCapability,\n type OperationOptions,\n type PendingChange,\n type PluginContext,\n} from '@embedpdf/core';\nimport type {\n Annotation,\n Attachment,\n AttachmentContent,\n AttachmentFileSource,\n ChangeItem,\n ChangeOp,\n ChangeResult,\n DocumentEvent,\n} from '@embedpdf/engine-core/runtime';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport type {\n AttachedFile,\n AttachmentCapability,\n AttachmentsChangedEvent,\n AttachmentsResyncedEvent,\n} from './contract';\nimport {\n documentFileOf,\n freeName,\n pageFileOf,\n selected,\n type AttachmentModel,\n type DocumentFiles,\n} from './model';\nimport { displayNameOf } from './names';\nimport { foldFiles, predictFiles, undoOf } from './sync/files';\n\nconst MODIFY: DocCapability = 'doc.attachments.modify';\nconst DOWNLOAD: DocCapability = 'doc.download';\n\nconst NO_FILES: readonly AttachedFile[] = Object.freeze([]);\n\n/**\n * The attachments controller. The document's attachments are a mirror,\n * read when something asks for them (`ensureLoaded()`, what\n * `attachmentState` does), and every read shows its `view()`: the engine's\n * attachments with this session's pending adds and removes on top. A page's\n * file is a file attachment annotation, read from the annotation plugin, so\n * the list shows both homes with no read of its own. Each add or remove of\n * an attachment is one change on the document's queue: it shows at once, is\n * one step of the history, and undoing it shows the files as they were.\n */\nexport function createAttachmentController(ctx: PluginContext<AttachmentModel>) {\n const changed = ctx.events.source<AttachmentsChangedEvent>();\n const resynced = ctx.events.source<AttachmentsResyncedEvent>();\n\n // One `AttachedFile` per record, so a list row keeps its object while its file is unchanged.\n const documentFiles = new WeakMap<Attachment, AttachedFile>();\n const fileOfAttachment = (attachment: Attachment): AttachedFile => {\n let file = documentFiles.get(attachment);\n if (!file) documentFiles.set(attachment, (file = documentFileOf(attachment)));\n return file;\n };\n const pageFiles = new WeakMap<Annotation, AttachedFile | null>();\n const fileOfAnnotation = (annotation: Annotation): AttachedFile | null => {\n let file = pageFiles.get(annotation);\n if (file === undefined) pageFiles.set(annotation, (file = pageFileOf(annotation)));\n return file;\n };\n\n /** The fact a confirmed attachment event reports, or `null` for any other event. */\n const factOf = (\n event: DocumentEvent,\n previous: DocumentFiles,\n ): Omit<AttachmentsChangedEvent, 'origin'> | null => {\n switch (event.type) {\n case 'attachments.created':\n return { type: 'added', files: [fileOfAttachment(event.attachment)] };\n case 'attachments.restored':\n return { type: 'restored', files: [fileOfAttachment(event.attachment)] };\n case 'attachments.deleted': {\n const gone = previous?.find((file) => file.ref.key === event.deleted?.key);\n return { type: 'removed', files: gone ? [fileOfAttachment(gone)] : [] };\n }\n default:\n return null;\n }\n };\n\n const files = ctx.mirror<DocumentFiles>({\n name: 'attachments',\n onDemand: true,\n initial: () => null,\n load: async (doc) => ({ value: (await doc.attachments.list()).attachments }),\n fold: foldFiles,\n predict: predictFiles,\n changed: ({ cause, event, previous, next }) => {\n if (!next) return;\n if (cause === 'load') {\n resynced.emit({ files: next.map(fileOfAttachment) });\n return;\n }\n const fact = event && 'origin' in event ? factOf(event, previous) : null;\n if (fact && event && 'origin' in event) changed.emit({ ...fact, origin: event.origin });\n },\n });\n\n const annotations = () => ctx.tryGet(AnnotationToken);\n\n /* ── reads ─────────────────────────────────────────────────────────────── */\n\n const list = memo(\n () => [files.view(), annotations()?.list() ?? null] as const,\n (attachments, annots) => {\n const all = [\n ...(attachments ?? []).map(fileOfAttachment),\n ...(annots ?? []).flatMap((annotation) => {\n const file = fileOfAnnotation(annotation);\n return file ? [file] : [];\n }),\n ];\n return all.length > 0 ? all : NO_FILES;\n },\n );\n const get = (id: string): AttachedFile | null => list().find((file) => file.id === id) ?? null;\n const getSelected = memo(\n () => [list(), ctx.state.get().selected] as const,\n (files, ids) => {\n if (ids.length === 0) return NO_FILES;\n const byId = new Map(files.map((file) => [file.id, file]));\n const chosen = ids.flatMap((id) => {\n const file = byId.get(id);\n return file ? [file] : [];\n });\n return chosen.length > 0 ? chosen : NO_FILES;\n },\n );\n\n const isPending = (file: AttachedFile): boolean => {\n if (file.home.kind === 'page') return annotations()?.isPending(file.home.ref) ?? false;\n const key = file.home.ref.key;\n return !(files.get() ?? []).some((confirmed) => confirmed.ref.key === key);\n };\n\n /* ── writes ────────────────────────────────────────────────────────────── */\n\n /** Refuse before anything starts: without the permission, or once the caller cancelled. */\n const refuse = (permission: DocCapability, operation: string, options?: OperationOptions) => {\n ctx.assertAllowed(permission, operation);\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'attachment', `${operation} was cancelled`);\n }\n };\n\n /** The engine's answer to a staged change. */\n const answer = async (\n change: PendingChange,\n options?: OperationOptions,\n ): Promise<ChangeResult> => {\n try {\n return await ctx.cancellable(options?.signal, change.result);\n } catch (error) {\n throw toPluginError('attachment', error);\n }\n };\n\n /** The annotation plugin, for a page's file: the list shows none without it. */\n const annotationsFor = (operation: string) => {\n const annotation = annotations();\n if (!annotation) {\n throw new PluginError('not-found', 'attachment', `${operation}: no annotation plugin`);\n }\n return annotation;\n };\n\n /** The op that attaches `source` under a name no file has (`taken`, which it joins). */\n const createOp = (source: AttachmentFileSource, taken: Set<string>): ChangeOp => {\n const { data, description } = source;\n const blob = typeof Blob !== 'undefined' && data instanceof Blob ? data : null;\n const given = source.name ?? (blob && 'name' in blob ? String(blob.name) : '');\n if (!given) {\n throw new PluginError(\n 'invalid-input',\n 'attachment',\n 'attachment.add: a file needs a name: pass { data, name } or a File',\n );\n }\n const name = freeName(given, taken);\n taken.add(name);\n const mimeType = source.mimeType ?? (blob?.type || undefined);\n return {\n type: 'attachments.create',\n file: {\n name,\n ...(mimeType !== undefined ? { mimeType } : {}),\n ...(description !== undefined ? { description } : {}),\n },\n resources: { file: data instanceof ArrayBuffer ? new Uint8Array(data) : data },\n };\n };\n\n const add: AttachmentCapability['add'] = async (sources, options) => {\n refuse(MODIFY, 'attachment.add', options);\n if (sources.length === 0) return NO_FILES;\n // The names in the document decide the free ones, so they are read first.\n await ctx.cancellable(options?.signal, files.ensureLoaded());\n const taken = new Set((files.view() ?? []).map((file) => file.ref.key));\n const ops = sources.map((source) => createOp(source, taken));\n const change = ctx.changes.stage({\n label: { key: 'attachment.add', count: ops.length },\n ops,\n undo: undoOf(files.view(), ops),\n });\n const result = await answer(change, options);\n return result.items.flatMap((item: ChangeItem) =>\n item.type === 'attachments.create' ? [fileOfAttachment(item.attachment)] : [],\n );\n };\n\n const remove: AttachmentCapability['remove'] = async (file, options) => {\n if (file.home.kind === 'page') {\n return annotationsFor('attachment.remove').delete(file.home.ref, options);\n }\n refuse(MODIFY, 'attachment.remove', options);\n const { ref } = file.home;\n const view = files.view();\n if (view && !view.some((attachment) => attachment.ref.key === ref.key)) {\n throw new PluginError(\n 'not-found',\n 'attachment',\n `attachment.remove: the document has no attachment '${ref.key}'`,\n );\n }\n const ops: ChangeOp[] = [{ type: 'attachments.delete', ref }];\n const change = ctx.changes.stage({\n label: { key: 'attachment.remove' },\n ops,\n undo: undoOf(view, ops),\n });\n await answer(change, options);\n };\n\n const download: AttachmentCapability['download'] = async (file, options) => {\n const content = (bytes: Uint8Array): AttachmentContent => ({\n bytes,\n name: displayNameOf(file),\n mimeType: file.mimeType,\n });\n if (file.home.kind === 'page') {\n const annotation = annotationsFor('attachment.download');\n return content(await annotation.downloadResource(file.home.ref, 'file', options));\n }\n refuse(DOWNLOAD, 'attachment.download', options);\n // A file this session is still adding is read once the engine has it.\n if (isPending(file)) await ctx.cancellable(options?.signal, ctx.changes.whenSettled());\n try {\n return content(\n await ctx.cancellable(options?.signal, ctx.doc.attachments.download(file.home.ref)),\n );\n } catch (error) {\n throw toPluginError('attachment', error);\n }\n };\n\n const reveal = (file: AttachedFile): void => {\n if (file.home.kind !== 'page') return;\n const annotation = annotations();\n const record = annotation?.get(file.home.ref);\n if (!annotation || !record) return;\n annotation.selection.set([record.ref]);\n // The file lands a third down the view, as a comment's annotation does.\n ctx.tryGet(StageToken)?.reveal(record.ref.page, {\n rect: record.rect,\n anchor: { x: 'center', y: 0.35 },\n behavior: 'smooth',\n });\n };\n\n const api: AttachmentCapability = {\n list,\n get,\n getSelected,\n select: (files) => ctx.state.update(selected, files.map((file) => file.id)),\n isPending,\n getStatus: files.getStatus,\n ensureLoaded: (options) => ctx.cancellable(options?.signal, files.ensureLoaded()),\n refresh: (options) => ctx.cancellable(options?.signal, files.refresh()),\n\n canDownload: () => ctx.allows(DOWNLOAD),\n canAdd: () => ctx.allows(MODIFY),\n canRemove: (file) =>\n file.home.kind === 'page'\n ? (annotations()?.canDelete(file.home.ref) ?? false)\n : ctx.allows(MODIFY),\n\n add,\n remove,\n download,\n reveal,\n\n onChanged: changed.on,\n onResynced: resynced.on,\n };\n\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { AttachmentToken } from './contract';\nimport { createAttachmentController } from './controller';\nimport { initialAttachmentModel } from './model';\n\n/**\n * The files a document carries. Document-scoped; optionally uses the\n * annotations (a page's files, and removing and saving them) and the stage\n * (going to a page's file).\n */\nexport const attachmentPlugin = () =>\n definePlugin({\n id: 'attachment',\n token: AttachmentToken,\n scope: 'document',\n optional: [AnnotationToken, StageToken],\n state: initialAttachmentModel,\n create: createAttachmentController,\n });\n","/**\n * The attachment page's State table as code: what `useAttachmentState()`\n * returns, and the same fields in every other framework. Reading the state\n * loads the attachments (`ensure`): the first reader of a document starts\n * the read.\n */\nimport { defineState, type ResourceStatus } from '@embedpdf/core';\n\nimport { AttachmentToken, type AttachedFile } from './contract';\n\n/** The document's files, the selected ones, whether they're read, and what this session may do. */\nexport interface AttachmentState {\n /** Every file the document carries: its attachments, then the files of its file attachment annotations. */\n readonly files: readonly AttachedFile[];\n /** The selected files, in the order they were selected. */\n readonly selected: readonly AttachedFile[];\n /** `idle` until something reads the state, then `loading` and `ready`, or `forbidden` or `error`. */\n readonly status: ResourceStatus;\n /** Whether this session may add and remove attachments (`doc.attachments.modify`). */\n readonly canAdd: boolean;\n /** Whether this session may take files out (`doc.download`). */\n readonly canDownload: boolean;\n}\n\nexport const attachmentState = defineState(AttachmentToken, {\n read: (attachment): AttachmentState => ({\n files: attachment.list(),\n selected: attachment.getSelected(),\n status: attachment.getStatus(),\n canAdd: attachment.canAdd(),\n canDownload: attachment.canDownload(),\n }),\n empty: {\n files: [],\n selected: [],\n status: 'idle',\n canAdd: false,\n canDownload: false,\n },\n ensure: (attachment) => attachment.ensureLoaded(),\n});\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,gCAAiD,EAAE,UAAU,CAAC,EAAE;;AAG7E,SAAgB,SAAS,OAAwB,KAAyC;CACxF,MAAM,SAAS,IAAI,QAAQ,IAAI,MAAM,IAAI,QAAQ,EAAE,MAAM,CAAC;CAG1D,OADE,OAAO,WAAW,MAAM,SAAS,UAAU,OAAO,OAAO,IAAI,MAAM,OAAO,MAAM,SAAS,EAAE,IAC/E,QAAQ;EAAE,GAAG;EAAO,UAAU;CAAO;AACrD;;AAMA,MAAa,kBAAkB,QAA+B,OAAO,IAAI;;AAGzE,MAAa,cAAc,QAA+B,SAAA,GAAA,8BAAA,cAAA,CAAsB,GAAG;;AAGnF,SAAgB,eAAe,YAAsC;CACnE,MAAM,EAAE,KAAK,OAAO,QAAQ,GAAG,SAAS;CACxC,OAAO;EAAE,GAAG;EAAM,IAAI,eAAe,GAAG;EAAG,MAAM;GAAE,MAAM;GAAY;EAAI;CAAE;AAC7E;;AAGA,SAAgB,WAAW,YAA6C;CACtE,IAAI,WAAW,YAAY,qBAAqB,CAAC,WAAW,MAAM,OAAO;CACzE,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NameOf","StageToken","AttachmentToken","AnnotationToken","StageToken","AttachmentToken"],"sources":["../src/model.ts","../src/sync/files.ts","../src/controller.ts","../src/attachment.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The attachment model: the document's attachments as the mirror holds\n * them, how an attachment and a page's file become one `AttachedFile`, and\n * the name a new file takes. Pure.\n */\nimport {\n annotationKey,\n type Annotation,\n type AnnotationRef,\n type Attachment,\n type AttachmentRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { AttachedFile } from './contract';\n\n/** The session's part: the selected files, by id, in the order they were selected. */\nexport interface AttachmentModel {\n readonly selected: readonly string[];\n}\n\nexport const initialAttachmentModel = (): AttachmentModel => ({ selected: [] });\n\n/** Make these files the selection; the same ids leave the state as it is. */\nexport function selected(state: AttachmentModel, ids: readonly string[]): AttachmentModel {\n const unique = ids.filter((id, i) => ids.indexOf(id) === i);\n const same =\n unique.length === state.selected.length && unique.every((id, i) => id === state.selected[i]);\n return same ? state : { ...state, selected: unique };\n}\n\n/** The document's attachments, in the order its name tree keeps them; `null` before the first read lands. */\nexport type DocumentFiles = readonly Attachment[] | null;\n\n/** An attachment's id: its key. */\nexport const documentFileId = (ref: AttachmentRef): string => `doc:${ref.key}`;\n\n/** A page file's id: its annotation's key. */\nexport const pageFileId = (ref: AnnotationRef): string => `page:${annotationKey(ref)}`;\n\n/** An attachment as the list shows it. */\nexport function documentFileOf(attachment: Attachment): AttachedFile {\n const { ref, index: _index, ...info } = attachment;\n return { ...info, id: documentFileId(ref), home: { kind: 'document', ref } };\n}\n\n/** A file attachment annotation's file as the list shows it; `null` for another kind, or one without a file. */\nexport function pageFileOf(annotation: Annotation): AttachedFile | null {\n if (annotation.subtype !== 'file-attachment' || !annotation.file) return null;\n return {\n ...annotation.file,\n id: pageFileId(annotation.ref),\n home: { kind: 'page', ref: annotation.ref },\n };\n}\n\n/**\n * `name`, or, when a file has it already, the name with the first number\n * that makes it free: `notes (2).txt`, then `notes (3).txt`. The number goes\n * before the extension, as a file manager puts it.\n */\nexport function freeName(name: string, taken: ReadonlySet<string>): string {\n if (!taken.has(name)) return name;\n const dot = name.lastIndexOf('.');\n const stem = dot > 0 ? name.slice(0, dot) : name;\n const extension = dot > 0 ? name.slice(dot) : '';\n for (let number = 2; ; number++) {\n const candidate = `${stem} (${number})${extension}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n","/**\n * How the document's attachments change: `foldFiles` applies one confirmed\n * event, the mirror's `fold`; `predictFiles` applies one op of a pending\n * change by the engine's rules, the mirror's `predict`; `undoOf` says what\n * undoing ops looks like. Pure.\n */\nimport type { PredictedOp } from '@embedpdf/core';\nimport {\n toAttachmentRef,\n type Attachment,\n type ChangeOp,\n type DocumentEvent,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { DocumentFiles } from '../model';\n\ntype CreateOp = Extract<ChangeOp, { type: 'attachments.create' }>;\n\n/** The files with each `index` its position, keeping the files whose position held. */\nfunction indexed(files: readonly Attachment[]): readonly Attachment[] {\n return files.map((file, index) => (file.index === index ? file : { ...file, index }));\n}\n\nconst has = (files: readonly Attachment[], key: string): boolean =>\n files.some((file) => file.ref.key === key);\n\n/**\n * The files with `attachment` among them, before the first key that sorts\n * after its own, as the name tree puts a new entry; one with its key gives\n * way to it.\n */\nfunction withFile(files: readonly Attachment[], attachment: Attachment): readonly Attachment[] {\n const key = attachment.ref.key;\n const rest = files.filter((file) => file.ref.key !== key);\n const at = rest.findIndex((file) => file.ref.key > key);\n return indexed(\n at < 0 ? [...rest, attachment] : [...rest.slice(0, at), attachment, ...rest.slice(at)],\n );\n}\n\nfunction withoutFile(files: readonly Attachment[], key: string): readonly Attachment[] {\n return has(files, key) ? indexed(files.filter((file) => file.ref.key !== key)) : files;\n}\n\n/* ── confirmed events ────────────────────────────────────────────────────── */\n\n/** One confirmed event, applied with the record it carries. Before the first load there is nothing to apply it to. */\nexport function foldFiles(files: DocumentFiles, event: DocumentEvent): DocumentFiles {\n if (!files) return files;\n switch (event.type) {\n case 'attachments.created':\n case 'attachments.restored':\n return withFile(files, event.attachment);\n case 'attachments.deleted':\n return event.deleted ? withoutFile(files, event.deleted.key) : files;\n default:\n return files;\n }\n}\n\n/* ── pending changes ─────────────────────────────────────────────────────── */\n\n/** A file a create adds, as it shows until the engine answers: what the op says of it, and its size. */\nfunction predictedFile(op: CreateOp): Attachment {\n const bytes = op.resources.file;\n return {\n ref: toAttachmentRef(op.file.name),\n index: 0,\n name: op.file.name,\n mimeType: op.file.mimeType ?? null,\n description: op.file.description ?? null,\n sizeBytes:\n bytes === undefined ? null : bytes instanceof Uint8Array ? bytes.byteLength : bytes.size,\n md5: null,\n createdAt: null,\n modifiedAt: null,\n };\n}\n\n/**\n * One op of a change this session staged, shown before the engine answers,\n * by the engine's rules: a create of a name a file has, a delete of a file\n * that isn't there, and a restore of a name a file has change nothing.\n */\nexport function predictFiles(files: DocumentFiles, op: PredictedOp): DocumentFiles {\n if (!files) return files;\n switch (op.type) {\n case 'attachments.create':\n return has(files, op.file.name) ? files : withFile(files, predictedFile(op));\n case 'attachments.delete':\n return withoutFile(files, op.ref.key);\n case 'attachments.restore':\n return has(files, op.attachment.ref.key) ? files : withFile(files, op.attachment);\n default:\n return files;\n }\n}\n\n/** What undoing one op looks like, read off the files it applies to. */\nfunction undoOfOp(files: readonly Attachment[], op: ChangeOp): PredictedOp[] {\n switch (op.type) {\n case 'attachments.create':\n return [{ type: 'attachments.delete', ref: toAttachmentRef(op.file.name) }];\n case 'attachments.delete': {\n const attachment = files.find((file) => file.ref.key === op.ref.key);\n return attachment ? [{ type: 'attachments.restore', attachment }] : [];\n }\n default:\n return [];\n }\n}\n\n/**\n * What undoing `ops` looks like, read off the files they apply to, each op\n * on the files the ops before it leave; the last op is undone first.\n */\nexport function undoOf(files: DocumentFiles, ops: readonly ChangeOp[]): PredictedOp[] {\n if (!files) return [];\n const undo: PredictedOp[][] = [];\n let current = files;\n for (const op of ops) {\n undo.push(undoOfOp(current, op));\n current = predictFiles(current, op) ?? current;\n }\n return undo.reverse().flat();\n}\n","import {\n memo,\n PluginError,\n toPluginError,\n type DocCapability,\n type OperationOptions,\n type PendingChange,\n type PluginContext,\n} from '@embedpdf/core';\nimport type {\n Annotation,\n Attachment,\n AttachmentContent,\n AttachmentFileSource,\n ChangeItem,\n ChangeOp,\n ChangeResult,\n DocumentEvent,\n} from '@embedpdf/engine-core/runtime';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport type {\n AttachedFile,\n AttachmentCapability,\n AttachmentsChangedEvent,\n AttachmentsResyncedEvent,\n} from './contract';\nimport {\n documentFileOf,\n freeName,\n pageFileOf,\n selected,\n type AttachmentModel,\n type DocumentFiles,\n} from './model';\nimport { displayNameOf } from './names';\nimport { foldFiles, predictFiles, undoOf } from './sync/files';\n\nconst MODIFY: DocCapability = 'doc.attachments.modify';\nconst DOWNLOAD: DocCapability = 'doc.download';\n\nconst NO_FILES: readonly AttachedFile[] = Object.freeze([]);\n\n/**\n * The attachments controller. The document's attachments are a mirror,\n * read when something asks for them (`ensureLoaded()`, what\n * `attachmentState` does), and every read shows its `view()`: the engine's\n * attachments with this session's pending adds and removes on top. A page's\n * file is a file attachment annotation, read from the annotation plugin, so\n * the list shows both homes with no read of its own. Each add or remove of\n * an attachment is one change on the document's queue: it shows at once, is\n * one step of the history, and undoing it shows the files as they were.\n */\nexport function createAttachmentController(ctx: PluginContext<AttachmentModel>) {\n const changed = ctx.events.source<AttachmentsChangedEvent>();\n const resynced = ctx.events.source<AttachmentsResyncedEvent>();\n\n // One `AttachedFile` per record, so a list row keeps its object while its file is unchanged.\n const documentFiles = new WeakMap<Attachment, AttachedFile>();\n const fileOfAttachment = (attachment: Attachment): AttachedFile => {\n let file = documentFiles.get(attachment);\n if (!file) documentFiles.set(attachment, (file = documentFileOf(attachment)));\n return file;\n };\n const pageFiles = new WeakMap<Annotation, AttachedFile | null>();\n const fileOfAnnotation = (annotation: Annotation): AttachedFile | null => {\n let file = pageFiles.get(annotation);\n if (file === undefined) pageFiles.set(annotation, (file = pageFileOf(annotation)));\n return file;\n };\n\n /** The fact a confirmed attachment event reports, or `null` for any other event. */\n const factOf = (\n event: DocumentEvent,\n previous: DocumentFiles,\n ): Omit<AttachmentsChangedEvent, 'origin'> | null => {\n switch (event.type) {\n case 'attachments.created':\n return { type: 'created', files: [fileOfAttachment(event.attachment)] };\n case 'attachments.restored':\n return { type: 'restored', files: [fileOfAttachment(event.attachment)] };\n case 'attachments.deleted': {\n const gone = previous?.find((file) => file.ref.key === event.deleted?.key);\n return { type: 'deleted', files: gone ? [fileOfAttachment(gone)] : [] };\n }\n default:\n return null;\n }\n };\n\n const files = ctx.mirror<DocumentFiles>({\n name: 'attachments',\n onDemand: true,\n initial: () => null,\n load: async (doc) => ({ value: (await doc.attachments.list()).attachments }),\n fold: foldFiles,\n predict: predictFiles,\n onChanged: ({ cause, event, previous, next }) => {\n if (!next) return;\n if (cause === 'load') {\n resynced.emit({ files: next.map(fileOfAttachment) });\n return;\n }\n const fact = event && 'origin' in event ? factOf(event, previous) : null;\n if (fact && event && 'origin' in event) changed.emit({ ...fact, origin: event.origin });\n },\n });\n\n const annotations = () => ctx.tryGet(AnnotationToken);\n\n /* ── reads ─────────────────────────────────────────────────────────────── */\n\n const list = memo(\n () => [files.view(), annotations()?.list() ?? null] as const,\n (attachments, annots) => {\n const all = [\n ...(attachments ?? []).map(fileOfAttachment),\n ...(annots ?? []).flatMap((annotation) => {\n const file = fileOfAnnotation(annotation);\n return file ? [file] : [];\n }),\n ];\n return all.length > 0 ? all : NO_FILES;\n },\n );\n const get = (id: string): AttachedFile | null => list().find((file) => file.id === id) ?? null;\n const getSelected = memo(\n () => [list(), ctx.state.get().selected] as const,\n (files, ids) => {\n if (ids.length === 0) return NO_FILES;\n const byId = new Map(files.map((file) => [file.id, file]));\n const chosen = ids.flatMap((id) => {\n const file = byId.get(id);\n return file ? [file] : [];\n });\n return chosen.length > 0 ? chosen : NO_FILES;\n },\n );\n\n const isPending = (file: AttachedFile): boolean => {\n if (file.home.kind === 'page') return annotations()?.isPending(file.home.ref) ?? false;\n const key = file.home.ref.key;\n return !(files.get() ?? []).some((confirmed) => confirmed.ref.key === key);\n };\n\n /* ── writes ────────────────────────────────────────────────────────────── */\n\n /** Refuse before anything starts: without the permission, or once the caller cancelled. */\n const refuse = (permission: DocCapability, operation: string, options?: OperationOptions) => {\n ctx.assertAllowed(permission, operation);\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'attachment', `${operation} was cancelled`);\n }\n };\n\n /** The engine's answer to a staged change. */\n const answer = async (\n change: PendingChange,\n options?: OperationOptions,\n ): Promise<ChangeResult> => {\n try {\n return await ctx.cancellable(options?.signal, change.result);\n } catch (error) {\n throw toPluginError('attachment', error);\n }\n };\n\n /** The annotation plugin, for a page's file: the list shows none without it. */\n const annotationsFor = (operation: string) => {\n const annotation = annotations();\n if (!annotation) {\n throw new PluginError('not-found', 'attachment', `${operation}: no annotation plugin`);\n }\n return annotation;\n };\n\n /** The op that attaches `source` under a name no file has (`taken`, which it joins). */\n const createOp = (source: AttachmentFileSource, taken: Set<string>): ChangeOp => {\n const { data, description } = source;\n const blob = typeof Blob !== 'undefined' && data instanceof Blob ? data : null;\n const given = source.name ?? (blob && 'name' in blob ? String(blob.name) : '');\n if (!given) {\n throw new PluginError(\n 'invalid-input',\n 'attachment',\n 'attachment.add: a file needs a name: pass { data, name } or a File',\n );\n }\n const name = freeName(given, taken);\n taken.add(name);\n const mimeType = source.mimeType ?? (blob?.type || undefined);\n return {\n type: 'attachments.create',\n file: {\n name,\n ...(mimeType !== undefined ? { mimeType } : {}),\n ...(description !== undefined ? { description } : {}),\n },\n resources: { file: data instanceof ArrayBuffer ? new Uint8Array(data) : data },\n };\n };\n\n const create: AttachmentCapability['create'] = async (sources, options) => {\n refuse(MODIFY, 'attachment.add', options);\n if (sources.length === 0) return NO_FILES;\n // The names in the document decide the free ones, so they are read first.\n await ctx.cancellable(options?.signal, files.ensureLoaded());\n const taken = new Set((files.view() ?? []).map((file) => file.ref.key));\n const ops = sources.map((source) => createOp(source, taken));\n const change = ctx.changes.stage({\n label: { key: 'attachment.add', count: ops.length },\n ops,\n undo: undoOf(files.view(), ops),\n });\n const result = await answer(change, options);\n return result.items.flatMap((item: ChangeItem) =>\n item.type === 'attachments.create' ? [fileOfAttachment(item.attachment)] : [],\n );\n };\n\n const remove: AttachmentCapability['delete'] = async (file, options) => {\n if (file.home.kind === 'page') {\n return annotationsFor('attachment.remove').delete(file.home.ref, options);\n }\n refuse(MODIFY, 'attachment.remove', options);\n const { ref } = file.home;\n const view = files.view();\n if (view && !view.some((attachment) => attachment.ref.key === ref.key)) {\n throw new PluginError(\n 'not-found',\n 'attachment',\n `attachment.remove: the document has no attachment '${ref.key}'`,\n );\n }\n const ops: ChangeOp[] = [{ type: 'attachments.delete', ref }];\n const change = ctx.changes.stage({\n label: { key: 'attachment.remove' },\n ops,\n undo: undoOf(view, ops),\n });\n await answer(change, options);\n };\n\n const download: AttachmentCapability['download'] = async (file, options) => {\n const content = (bytes: Uint8Array): AttachmentContent => ({\n bytes,\n name: displayNameOf(file),\n mimeType: file.mimeType,\n });\n if (file.home.kind === 'page') {\n const annotation = annotationsFor('attachment.download');\n return content(await annotation.downloadResource(file.home.ref, 'file', options));\n }\n refuse(DOWNLOAD, 'attachment.download', options);\n // A file this session is still adding is read once the engine has it.\n if (isPending(file)) await ctx.cancellable(options?.signal, ctx.changes.whenSettled());\n try {\n return content(\n await ctx.cancellable(options?.signal, ctx.doc.attachments.download(file.home.ref)),\n );\n } catch (error) {\n throw toPluginError('attachment', error);\n }\n };\n\n const reveal = (file: AttachedFile): void => {\n if (file.home.kind !== 'page') return;\n const annotation = annotations();\n const record = annotation?.get(file.home.ref);\n if (!annotation || !record) return;\n annotation.selection.select([record.ref]);\n // The file lands a third down the view, as a comment's annotation does.\n ctx.tryGet(StageToken)?.reveal(record.ref.page, {\n rect: record.rect,\n align: { x: 'center', y: 0.35 },\n behavior: 'smooth',\n });\n };\n\n const api: AttachmentCapability = {\n list,\n get,\n getSelected,\n select: (files) =>\n ctx.state.update(\n selected,\n files.map((file) => file.id),\n ),\n isPending,\n getStatus: files.getStatus,\n ensureLoaded: (options) => ctx.cancellable(options?.signal, files.ensureLoaded()),\n refresh: (options) => ctx.cancellable(options?.signal, files.refresh()),\n\n canDownload: () => ctx.allows(DOWNLOAD),\n canCreate: () => ctx.allows(MODIFY),\n canDelete: (file) =>\n file.home.kind === 'page'\n ? (annotations()?.canDelete(file.home.ref) ?? false)\n : ctx.allows(MODIFY),\n\n create,\n delete: remove,\n download,\n reveal,\n\n onChanged: changed.on,\n onResynced: resynced.on,\n };\n\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { AttachmentToken } from './contract';\nimport { createAttachmentController } from './controller';\nimport { initialAttachmentModel } from './model';\n\n/**\n * The files a document carries. Document-scoped; optionally uses the\n * annotations (a page's files, and removing and saving them) and the stage\n * (going to a page's file).\n */\nexport const attachmentPlugin = () =>\n definePlugin({\n id: 'attachment',\n token: AttachmentToken,\n scope: 'document',\n optional: [AnnotationToken, StageToken],\n state: initialAttachmentModel,\n create: createAttachmentController,\n });\n","/**\n * The attachment page's State table as code: what `useAttachmentState()`\n * returns, and the same fields in every other framework. Reading the state\n * loads the attachments (`ensure`): the first reader of a document starts\n * the read.\n */\nimport { defineState, type ResourceStatus } from '@embedpdf/core';\n\nimport { AttachmentToken, type AttachedFile } from './contract';\n\n/** The document's files, the selected ones, whether they're read, and what this session may do. */\nexport interface AttachmentState {\n /** Every file the document carries: its attachments, then the files of its file attachment annotations. */\n readonly files: readonly AttachedFile[];\n /** The selected files, in the order they were selected. */\n readonly selected: readonly AttachedFile[];\n /** `idle` until something reads the state, then `loading` and `ready`, or `forbidden` or `error`. */\n readonly status: ResourceStatus;\n /** Whether this session may add and remove attachments (`doc.attachments.modify`). */\n readonly canCreate: boolean;\n /** Whether this session may take files out (`doc.download`). */\n readonly canDownload: boolean;\n}\n\nexport const attachmentState = defineState(AttachmentToken, {\n read: (attachment): AttachmentState => ({\n files: attachment.list(),\n selected: attachment.getSelected(),\n status: attachment.getStatus(),\n canCreate: attachment.canCreate(),\n canDownload: attachment.canDownload(),\n }),\n empty: {\n files: [],\n selected: [],\n status: 'idle',\n canCreate: false,\n canDownload: false,\n },\n ensure: (attachment) => attachment.ensureLoaded(),\n});\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,gCAAiD,EAAE,UAAU,CAAC,EAAE;;AAG7E,SAAgB,SAAS,OAAwB,KAAyC;CACxF,MAAM,SAAS,IAAI,QAAQ,IAAI,MAAM,IAAI,QAAQ,EAAE,MAAM,CAAC;CAG1D,OADE,OAAO,WAAW,MAAM,SAAS,UAAU,OAAO,OAAO,IAAI,MAAM,OAAO,MAAM,SAAS,EAAE,IAC/E,QAAQ;EAAE,GAAG;EAAO,UAAU;CAAO;AACrD;;AAMA,MAAa,kBAAkB,QAA+B,OAAO,IAAI;;AAGzE,MAAa,cAAc,QAA+B,SAAA,GAAA,8BAAA,cAAA,CAAsB,GAAG;;AAGnF,SAAgB,eAAe,YAAsC;CACnE,MAAM,EAAE,KAAK,OAAO,QAAQ,GAAG,SAAS;CACxC,OAAO;EAAE,GAAG;EAAM,IAAI,eAAe,GAAG;EAAG,MAAM;GAAE,MAAM;GAAY;EAAI;CAAE;AAC7E;;AAGA,SAAgB,WAAW,YAA6C;CACtE,IAAI,WAAW,YAAY,qBAAqB,CAAC,WAAW,MAAM,OAAO;CACzE,OAAO;EACL,GAAG,WAAW;EACd,IAAI,WAAW,WAAW,GAAG;EAC7B,MAAM;GAAE,MAAM;GAAQ,KAAK,WAAW;EAAI;CAC5C;AACF;;;;;;AAOA,SAAgB,SAAS,MAAc,OAAoC;CACzE,IAAI,CAAC,MAAM,IAAI,IAAI,GAAG,OAAO;CAC7B,M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AM,KAAK,SAAS,KAAK,EAAE,CAC7B;EACF;EACA,WAAW,MAAM;EACjB,eAAe,YAAY,IAAI,YAAY,SAAS,QAAQ,MAAM,aAAa,CAAC;EAChF,UAAU,YAAY,IAAI,YAAY,SAAS,QAAQ,MAAM,QAAQ,CAAC;EAEtE,mBAAmB,IAAI,OAAO,QAAQ;EACtC,iBAAiB,IAAI,OAAO,MAAM;EAClC,YAAY,SACV,KAAK,KAAK,SAAS,SACd,YAAY,CAAC,EAAE,UAAU,KAAK,KAAK,GAAG,KAAK,QAC5C,IAAI,OAAO,MAAM;EAEvB;EACA,QAAQ;EACR;EACA;EAEA,WAAW,QAAQ;EACnB,YAAY,SAAS;CAGZ,EAAE;AACf;;;;;;;;AC1SA,MAAa,0BAAA,GAAA,eAAA,aAAA,CACE;CACX,IAAI;CACJ,OAAOC,iBAAAA;CACP,OAAO;CACP,UAAU,CAACC,qCAAAA,iBAAiBC,gCAAAA,UAAU;CACtC,OAAO;CACP,QAAQ;AACV,CAAC;;;;;;;;;ACGH,MAAa,mBAAA,GAAA,eAAA,YAAA,CAA8BC,iBAAAA,iBAAiB;CAC1D,OAAO,gBAAiC;EACtC,OAAO,WAAW,KAAK;EACvB,UAAU,WAAW,YAAY;EACjC,QAAQ,WAAW,UAAU;EAC7B,WAAW,WAAW,UAAU;EAChC,aAAa,WAAW,YAAY;CACtC;CACA,OAAO;EACL,OAAO,CAAC;EACR,UAAU,CAAC;EACX,QAAQ;EACR,WAAW;EACX,aAAa;CACf;CACA,SAAS,eAAe,WAAW,aAAa;AAClD,CAAC"}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AttachmentContent, c as AttachmentRef, d as displayNameOf, f as AttachmentToken, i as AttachmentCapability, l as AttachmentsChangedEvent, n as AttachedFile, o as AttachmentFileInfo, r as AttachedFileHome, s as AttachmentFileSource, t as AnnotationRef, u as AttachmentsResyncedEvent } from "./contract-D2t_jdnb.cjs";
1
+ import { a as AttachmentContent, c as AttachmentRef, d as displayNameOf, f as AttachmentToken, i as AttachmentCapability, l as AttachmentsChangedEvent, n as AttachedFile, o as AttachmentFileInfo, r as AttachedFileHome, s as AttachmentFileSource, t as AnnotationRef, u as AttachmentsResyncedEvent } from "./contract-G9XK_m9w.cjs";
2
2
  import { ResourceStatus } from "@embedpdf/core";
3
3
  import "@embedpdf/engine-core/runtime";
4
4
  //#region src/model.d.ts
@@ -13,7 +13,7 @@ interface AttachmentModel {
13
13
  * annotations (a page's files, and removing and saving them) and the stage
14
14
  * (going to a page's file).
15
15
  */
16
- declare const attachmentPlugin: () => import("@embedpdf/core").PluginDef<AttachmentModel, AttachmentCapability, import("@embedpdf/core").NoSettings>;
16
+ declare const attachmentPlugin: () => import("@embedpdf/core").PluginDefinition<AttachmentModel, AttachmentCapability, import("@embedpdf/core").NoSettings>;
17
17
  //#endregion
18
18
  //#region src/state.d.ts
19
19
  /** The document's files, the selected ones, whether they're read, and what this session may do. */
@@ -25,7 +25,7 @@ interface AttachmentState {
25
25
  /** `idle` until something reads the state, then `loading` and `ready`, or `forbidden` or `error`. */
26
26
  readonly status: ResourceStatus;
27
27
  /** Whether this session may add and remove attachments (`doc.attachments.modify`). */
28
- readonly canAdd: boolean;
28
+ readonly canCreate: boolean;
29
29
  /** Whether this session may take files out (`doc.download`). */
30
30
  readonly canDownload: boolean;
31
31
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AttachmentContent, c as AttachmentRef, d as displayNameOf, f as AttachmentToken, i as AttachmentCapability, l as AttachmentsChangedEvent, n as AttachedFile, o as AttachmentFileInfo, r as AttachedFileHome, s as AttachmentFileSource, t as AnnotationRef, u as AttachmentsResyncedEvent } from "./contract-D2t_jdnb.js";
1
+ import { a as AttachmentContent, c as AttachmentRef, d as displayNameOf, f as AttachmentToken, i as AttachmentCapability, l as AttachmentsChangedEvent, n as AttachedFile, o as AttachmentFileInfo, r as AttachedFileHome, s as AttachmentFileSource, t as AnnotationRef, u as AttachmentsResyncedEvent } from "./contract-G9XK_m9w.js";
2
2
  import { ResourceStatus } from "@embedpdf/core";
3
3
  import "@embedpdf/engine-core/runtime";
4
4
  //#region src/model.d.ts
@@ -13,7 +13,7 @@ interface AttachmentModel {
13
13
  * annotations (a page's files, and removing and saving them) and the stage
14
14
  * (going to a page's file).
15
15
  */
16
- declare const attachmentPlugin: () => import("@embedpdf/core").PluginDef<AttachmentModel, AttachmentCapability, import("@embedpdf/core").NoSettings>;
16
+ declare const attachmentPlugin: () => import("@embedpdf/core").PluginDefinition<AttachmentModel, AttachmentCapability, import("@embedpdf/core").NoSettings>;
17
17
  //#endregion
18
18
  //#region src/state.d.ts
19
19
  /** The document's files, the selected ones, whether they're read, and what this session may do. */
@@ -25,7 +25,7 @@ interface AttachmentState {
25
25
  /** `idle` until something reads the state, then `loading` and `ready`, or `forbidden` or `error`. */
26
26
  readonly status: ResourceStatus;
27
27
  /** Whether this session may add and remove attachments (`doc.attachments.modify`). */
28
- readonly canAdd: boolean;
28
+ readonly canCreate: boolean;
29
29
  /** Whether this session may take files out (`doc.download`). */
30
30
  readonly canDownload: boolean;
31
31
  }
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as AttachmentToken, t as displayNameOf } from "./contract-CqFkPaxs.js";
1
+ import { n as AttachmentToken, t as displayNameOf } from "./contract-Bz7NXE3o.js";
2
2
  import { PluginError, definePlugin, defineState, memo, toPluginError } from "@embedpdf/core";
3
3
  import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
4
4
  import { StageToken } from "@embedpdf/plugin-stage/contract";
@@ -108,8 +108,8 @@ function predictedFile(op) {
108
108
  name: op.file.name,
109
109
  mimeType: op.file.mimeType ?? null,
110
110
  description: op.file.description ?? null,
111
- size: bytes === void 0 ? null : bytes instanceof Uint8Array ? bytes.byteLength : bytes.size,
112
- checksum: null,
111
+ sizeBytes: bytes === void 0 ? null : bytes instanceof Uint8Array ? bytes.byteLength : bytes.size,
112
+ md5: null,
113
113
  createdAt: null,
114
114
  modifiedAt: null
115
115
  };
@@ -193,7 +193,7 @@ function createAttachmentController(ctx) {
193
193
  const factOf = (event, previous) => {
194
194
  switch (event.type) {
195
195
  case "attachments.created": return {
196
- type: "added",
196
+ type: "created",
197
197
  files: [fileOfAttachment(event.attachment)]
198
198
  };
199
199
  case "attachments.restored": return {
@@ -203,7 +203,7 @@ function createAttachmentController(ctx) {
203
203
  case "attachments.deleted": {
204
204
  const gone = previous?.find((file) => file.ref.key === event.deleted?.key);
205
205
  return {
206
- type: "removed",
206
+ type: "deleted",
207
207
  files: gone ? [fileOfAttachment(gone)] : []
208
208
  };
209
209
  }
@@ -217,7 +217,7 @@ function createAttachmentController(ctx) {
217
217
  load: async (doc) => ({ value: (await doc.attachments.list()).attachments }),
218
218
  fold: foldFiles,
219
219
  predict: predictFiles,
220
- changed: ({ cause, event, previous, next }) => {
220
+ onChanged: ({ cause, event, previous, next }) => {
221
221
  if (!next) return;
222
222
  if (cause === "load") {
223
223
  resynced.emit({ files: next.map(fileOfAttachment) });
@@ -291,7 +291,7 @@ function createAttachmentController(ctx) {
291
291
  resources: { file: data instanceof ArrayBuffer ? new Uint8Array(data) : data }
292
292
  };
293
293
  };
294
- const add = async (sources, options) => {
294
+ const create = async (sources, options) => {
295
295
  refuse(MODIFY, "attachment.add", options);
296
296
  if (sources.length === 0) return NO_FILES;
297
297
  await ctx.cancellable(options?.signal, files.ensureLoaded());
@@ -344,10 +344,10 @@ function createAttachmentController(ctx) {
344
344
  const annotation = annotations();
345
345
  const record = annotation?.get(file.home.ref);
346
346
  if (!annotation || !record) return;
347
- annotation.selection.set([record.ref]);
347
+ annotation.selection.select([record.ref]);
348
348
  ctx.tryGet(StageToken)?.reveal(record.ref.page, {
349
349
  rect: record.rect,
350
- anchor: {
350
+ align: {
351
351
  x: "center",
352
352
  y: .35
353
353
  },
@@ -364,10 +364,10 @@ function createAttachmentController(ctx) {
364
364
  ensureLoaded: (options) => ctx.cancellable(options?.signal, files.ensureLoaded()),
365
365
  refresh: (options) => ctx.cancellable(options?.signal, files.refresh()),
366
366
  canDownload: () => ctx.allows(DOWNLOAD),
367
- canAdd: () => ctx.allows(MODIFY),
368
- canRemove: (file) => file.home.kind === "page" ? annotations()?.canDelete(file.home.ref) ?? false : ctx.allows(MODIFY),
369
- add,
370
- remove,
367
+ canCreate: () => ctx.allows(MODIFY),
368
+ canDelete: (file) => file.home.kind === "page" ? annotations()?.canDelete(file.home.ref) ?? false : ctx.allows(MODIFY),
369
+ create,
370
+ delete: remove,
371
371
  download,
372
372
  reveal,
373
373
  onChanged: changed.on,
@@ -402,14 +402,14 @@ const attachmentState = defineState(AttachmentToken, {
402
402
  files: attachment.list(),
403
403
  selected: attachment.getSelected(),
404
404
  status: attachment.getStatus(),
405
- canAdd: attachment.canAdd(),
405
+ canCreate: attachment.canCreate(),
406
406
  canDownload: attachment.canDownload()
407
407
  }),
408
408
  empty: {
409
409
  files: [],
410
410
  selected: [],
411
411
  status: "idle",
412
- canAdd: false,
412
+ canCreate: false,
413
413
  canDownload: false
414
414
  },
415
415
  ensure: (attachment) => attachment.ensureLoaded()
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/model.ts","../src/sync/files.ts","../src/controller.ts","../src/attachment.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The attachment model: the document's attachments as the mirror holds\n * them, how an attachment and a page's file become one `AttachedFile`, and\n * the name a new file takes. Pure.\n */\nimport {\n annotationKey,\n type Annotation,\n type AnnotationRef,\n type Attachment,\n type AttachmentRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { AttachedFile } from './contract';\n\n/** The session's part: the selected files, by id, in the order they were selected. */\nexport interface AttachmentModel {\n readonly selected: readonly string[];\n}\n\nexport const initialAttachmentModel = (): AttachmentModel => ({ selected: [] });\n\n/** Make these files the selection; the same ids leave the state as it is. */\nexport function selected(state: AttachmentModel, ids: readonly string[]): AttachmentModel {\n const unique = ids.filter((id, i) => ids.indexOf(id) === i);\n const same =\n unique.length === state.selected.length && unique.every((id, i) => id === state.selected[i]);\n return same ? state : { ...state, selected: unique };\n}\n\n/** The document's attachments, in the order its name tree keeps them; `null` before the first read lands. */\nexport type DocumentFiles = readonly Attachment[] | null;\n\n/** An attachment's id: its key. */\nexport const documentFileId = (ref: AttachmentRef): string => `doc:${ref.key}`;\n\n/** A page file's id: its annotation's key. */\nexport const pageFileId = (ref: AnnotationRef): string => `page:${annotationKey(ref)}`;\n\n/** An attachment as the list shows it. */\nexport function documentFileOf(attachment: Attachment): AttachedFile {\n const { ref, index: _index, ...info } = attachment;\n return { ...info, id: documentFileId(ref), home: { kind: 'document', ref } };\n}\n\n/** A file attachment annotation's file as the list shows it; `null` for another kind, or one without a file. */\nexport function pageFileOf(annotation: Annotation): AttachedFile | null {\n if (annotation.subtype !== 'file-attachment' || !annotation.file) return null;\n return {\n ...annotation.file,\n id: pageFileId(annotation.ref),\n home: { kind: 'page', ref: annotation.ref },\n };\n}\n\n/**\n * `name`, or, when a file has it already, the name with the first number\n * that makes it free: `notes (2).txt`, then `notes (3).txt`. The number goes\n * before the extension, as a file manager puts it.\n */\nexport function freeName(name: string, taken: ReadonlySet<string>): string {\n if (!taken.has(name)) return name;\n const dot = name.lastIndexOf('.');\n const stem = dot > 0 ? name.slice(0, dot) : name;\n const extension = dot > 0 ? name.slice(dot) : '';\n for (let number = 2; ; number++) {\n const candidate = `${stem} (${number})${extension}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n","/**\n * How the document's attachments change: `foldFiles` applies one confirmed\n * event, the mirror's `fold`; `predictFiles` applies one op of a pending\n * change by the engine's rules, the mirror's `predict`; `undoOf` says what\n * undoing ops looks like. Pure.\n */\nimport type { PredictedOp } from '@embedpdf/core';\nimport {\n toAttachmentRef,\n type Attachment,\n type ChangeOp,\n type DocumentEvent,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { DocumentFiles } from '../model';\n\ntype CreateOp = Extract<ChangeOp, { type: 'attachments.create' }>;\n\n/** The files with each `index` its position, keeping the files whose position held. */\nfunction indexed(files: readonly Attachment[]): readonly Attachment[] {\n return files.map((file, index) => (file.index === index ? file : { ...file, index }));\n}\n\nconst has = (files: readonly Attachment[], key: string): boolean =>\n files.some((file) => file.ref.key === key);\n\n/**\n * The files with `attachment` among them, before the first key that sorts\n * after its own, as the name tree puts a new entry; one with its key gives\n * way to it.\n */\nfunction withFile(files: readonly Attachment[], attachment: Attachment): readonly Attachment[] {\n const key = attachment.ref.key;\n const rest = files.filter((file) => file.ref.key !== key);\n const at = rest.findIndex((file) => file.ref.key > key);\n return indexed(\n at < 0 ? [...rest, attachment] : [...rest.slice(0, at), attachment, ...rest.slice(at)],\n );\n}\n\nfunction withoutFile(files: readonly Attachment[], key: string): readonly Attachment[] {\n return has(files, key) ? indexed(files.filter((file) => file.ref.key !== key)) : files;\n}\n\n/* ── confirmed events ────────────────────────────────────────────────────── */\n\n/** One confirmed event, applied with the record it carries. Before the first load there is nothing to apply it to. */\nexport function foldFiles(files: DocumentFiles, event: DocumentEvent): DocumentFiles {\n if (!files) return files;\n switch (event.type) {\n case 'attachments.created':\n case 'attachments.restored':\n return withFile(files, event.attachment);\n case 'attachments.deleted':\n return event.deleted ? withoutFile(files, event.deleted.key) : files;\n default:\n return files;\n }\n}\n\n/* ── pending changes ─────────────────────────────────────────────────────── */\n\n/** A file a create adds, as it shows until the engine answers: what the op says of it, and its size. */\nfunction predictedFile(op: CreateOp): Attachment {\n const bytes = op.resources.file;\n return {\n ref: toAttachmentRef(op.file.name),\n index: 0,\n name: op.file.name,\n mimeType: op.file.mimeType ?? null,\n description: op.file.description ?? null,\n size: bytes === undefined ? null : bytes instanceof Uint8Array ? bytes.byteLength : bytes.size,\n checksum: null,\n createdAt: null,\n modifiedAt: null,\n };\n}\n\n/**\n * One op of a change this session staged, shown before the engine answers,\n * by the engine's rules: a create of a name a file has, a delete of a file\n * that isn't there, and a restore of a name a file has change nothing.\n */\nexport function predictFiles(files: DocumentFiles, op: PredictedOp): DocumentFiles {\n if (!files) return files;\n switch (op.type) {\n case 'attachments.create':\n return has(files, op.file.name) ? files : withFile(files, predictedFile(op));\n case 'attachments.delete':\n return withoutFile(files, op.ref.key);\n case 'attachments.restore':\n return has(files, op.attachment.ref.key) ? files : withFile(files, op.attachment);\n default:\n return files;\n }\n}\n\n/** What undoing one op looks like, read off the files it applies to. */\nfunction undoOfOp(files: readonly Attachment[], op: ChangeOp): PredictedOp[] {\n switch (op.type) {\n case 'attachments.create':\n return [{ type: 'attachments.delete', ref: toAttachmentRef(op.file.name) }];\n case 'attachments.delete': {\n const attachment = files.find((file) => file.ref.key === op.ref.key);\n return attachment ? [{ type: 'attachments.restore', attachment }] : [];\n }\n default:\n return [];\n }\n}\n\n/**\n * What undoing `ops` looks like, read off the files they apply to, each op\n * on the files the ops before it leave; the last op is undone first.\n */\nexport function undoOf(files: DocumentFiles, ops: readonly ChangeOp[]): PredictedOp[] {\n if (!files) return [];\n const undo: PredictedOp[][] = [];\n let current = files;\n for (const op of ops) {\n undo.push(undoOfOp(current, op));\n current = predictFiles(current, op) ?? current;\n }\n return undo.reverse().flat();\n}\n","import {\n memo,\n PluginError,\n toPluginError,\n type DocCapability,\n type OperationOptions,\n type PendingChange,\n type PluginContext,\n} from '@embedpdf/core';\nimport type {\n Annotation,\n Attachment,\n AttachmentContent,\n AttachmentFileSource,\n ChangeItem,\n ChangeOp,\n ChangeResult,\n DocumentEvent,\n} from '@embedpdf/engine-core/runtime';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport type {\n AttachedFile,\n AttachmentCapability,\n AttachmentsChangedEvent,\n AttachmentsResyncedEvent,\n} from './contract';\nimport {\n documentFileOf,\n freeName,\n pageFileOf,\n selected,\n type AttachmentModel,\n type DocumentFiles,\n} from './model';\nimport { displayNameOf } from './names';\nimport { foldFiles, predictFiles, undoOf } from './sync/files';\n\nconst MODIFY: DocCapability = 'doc.attachments.modify';\nconst DOWNLOAD: DocCapability = 'doc.download';\n\nconst NO_FILES: readonly AttachedFile[] = Object.freeze([]);\n\n/**\n * The attachments controller. The document's attachments are a mirror,\n * read when something asks for them (`ensureLoaded()`, what\n * `attachmentState` does), and every read shows its `view()`: the engine's\n * attachments with this session's pending adds and removes on top. A page's\n * file is a file attachment annotation, read from the annotation plugin, so\n * the list shows both homes with no read of its own. Each add or remove of\n * an attachment is one change on the document's queue: it shows at once, is\n * one step of the history, and undoing it shows the files as they were.\n */\nexport function createAttachmentController(ctx: PluginContext<AttachmentModel>) {\n const changed = ctx.events.source<AttachmentsChangedEvent>();\n const resynced = ctx.events.source<AttachmentsResyncedEvent>();\n\n // One `AttachedFile` per record, so a list row keeps its object while its file is unchanged.\n const documentFiles = new WeakMap<Attachment, AttachedFile>();\n const fileOfAttachment = (attachment: Attachment): AttachedFile => {\n let file = documentFiles.get(attachment);\n if (!file) documentFiles.set(attachment, (file = documentFileOf(attachment)));\n return file;\n };\n const pageFiles = new WeakMap<Annotation, AttachedFile | null>();\n const fileOfAnnotation = (annotation: Annotation): AttachedFile | null => {\n let file = pageFiles.get(annotation);\n if (file === undefined) pageFiles.set(annotation, (file = pageFileOf(annotation)));\n return file;\n };\n\n /** The fact a confirmed attachment event reports, or `null` for any other event. */\n const factOf = (\n event: DocumentEvent,\n previous: DocumentFiles,\n ): Omit<AttachmentsChangedEvent, 'origin'> | null => {\n switch (event.type) {\n case 'attachments.created':\n return { type: 'added', files: [fileOfAttachment(event.attachment)] };\n case 'attachments.restored':\n return { type: 'restored', files: [fileOfAttachment(event.attachment)] };\n case 'attachments.deleted': {\n const gone = previous?.find((file) => file.ref.key === event.deleted?.key);\n return { type: 'removed', files: gone ? [fileOfAttachment(gone)] : [] };\n }\n default:\n return null;\n }\n };\n\n const files = ctx.mirror<DocumentFiles>({\n name: 'attachments',\n onDemand: true,\n initial: () => null,\n load: async (doc) => ({ value: (await doc.attachments.list()).attachments }),\n fold: foldFiles,\n predict: predictFiles,\n changed: ({ cause, event, previous, next }) => {\n if (!next) return;\n if (cause === 'load') {\n resynced.emit({ files: next.map(fileOfAttachment) });\n return;\n }\n const fact = event && 'origin' in event ? factOf(event, previous) : null;\n if (fact && event && 'origin' in event) changed.emit({ ...fact, origin: event.origin });\n },\n });\n\n const annotations = () => ctx.tryGet(AnnotationToken);\n\n /* ── reads ─────────────────────────────────────────────────────────────── */\n\n const list = memo(\n () => [files.view(), annotations()?.list() ?? null] as const,\n (attachments, annots) => {\n const all = [\n ...(attachments ?? []).map(fileOfAttachment),\n ...(annots ?? []).flatMap((annotation) => {\n const file = fileOfAnnotation(annotation);\n return file ? [file] : [];\n }),\n ];\n return all.length > 0 ? all : NO_FILES;\n },\n );\n const get = (id: string): AttachedFile | null => list().find((file) => file.id === id) ?? null;\n const getSelected = memo(\n () => [list(), ctx.state.get().selected] as const,\n (files, ids) => {\n if (ids.length === 0) return NO_FILES;\n const byId = new Map(files.map((file) => [file.id, file]));\n const chosen = ids.flatMap((id) => {\n const file = byId.get(id);\n return file ? [file] : [];\n });\n return chosen.length > 0 ? chosen : NO_FILES;\n },\n );\n\n const isPending = (file: AttachedFile): boolean => {\n if (file.home.kind === 'page') return annotations()?.isPending(file.home.ref) ?? false;\n const key = file.home.ref.key;\n return !(files.get() ?? []).some((confirmed) => confirmed.ref.key === key);\n };\n\n /* ── writes ────────────────────────────────────────────────────────────── */\n\n /** Refuse before anything starts: without the permission, or once the caller cancelled. */\n const refuse = (permission: DocCapability, operation: string, options?: OperationOptions) => {\n ctx.assertAllowed(permission, operation);\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'attachment', `${operation} was cancelled`);\n }\n };\n\n /** The engine's answer to a staged change. */\n const answer = async (\n change: PendingChange,\n options?: OperationOptions,\n ): Promise<ChangeResult> => {\n try {\n return await ctx.cancellable(options?.signal, change.result);\n } catch (error) {\n throw toPluginError('attachment', error);\n }\n };\n\n /** The annotation plugin, for a page's file: the list shows none without it. */\n const annotationsFor = (operation: string) => {\n const annotation = annotations();\n if (!annotation) {\n throw new PluginError('not-found', 'attachment', `${operation}: no annotation plugin`);\n }\n return annotation;\n };\n\n /** The op that attaches `source` under a name no file has (`taken`, which it joins). */\n const createOp = (source: AttachmentFileSource, taken: Set<string>): ChangeOp => {\n const { data, description } = source;\n const blob = typeof Blob !== 'undefined' && data instanceof Blob ? data : null;\n const given = source.name ?? (blob && 'name' in blob ? String(blob.name) : '');\n if (!given) {\n throw new PluginError(\n 'invalid-input',\n 'attachment',\n 'attachment.add: a file needs a name: pass { data, name } or a File',\n );\n }\n const name = freeName(given, taken);\n taken.add(name);\n const mimeType = source.mimeType ?? (blob?.type || undefined);\n return {\n type: 'attachments.create',\n file: {\n name,\n ...(mimeType !== undefined ? { mimeType } : {}),\n ...(description !== undefined ? { description } : {}),\n },\n resources: { file: data instanceof ArrayBuffer ? new Uint8Array(data) : data },\n };\n };\n\n const add: AttachmentCapability['add'] = async (sources, options) => {\n refuse(MODIFY, 'attachment.add', options);\n if (sources.length === 0) return NO_FILES;\n // The names in the document decide the free ones, so they are read first.\n await ctx.cancellable(options?.signal, files.ensureLoaded());\n const taken = new Set((files.view() ?? []).map((file) => file.ref.key));\n const ops = sources.map((source) => createOp(source, taken));\n const change = ctx.changes.stage({\n label: { key: 'attachment.add', count: ops.length },\n ops,\n undo: undoOf(files.view(), ops),\n });\n const result = await answer(change, options);\n return result.items.flatMap((item: ChangeItem) =>\n item.type === 'attachments.create' ? [fileOfAttachment(item.attachment)] : [],\n );\n };\n\n const remove: AttachmentCapability['remove'] = async (file, options) => {\n if (file.home.kind === 'page') {\n return annotationsFor('attachment.remove').delete(file.home.ref, options);\n }\n refuse(MODIFY, 'attachment.remove', options);\n const { ref } = file.home;\n const view = files.view();\n if (view && !view.some((attachment) => attachment.ref.key === ref.key)) {\n throw new PluginError(\n 'not-found',\n 'attachment',\n `attachment.remove: the document has no attachment '${ref.key}'`,\n );\n }\n const ops: ChangeOp[] = [{ type: 'attachments.delete', ref }];\n const change = ctx.changes.stage({\n label: { key: 'attachment.remove' },\n ops,\n undo: undoOf(view, ops),\n });\n await answer(change, options);\n };\n\n const download: AttachmentCapability['download'] = async (file, options) => {\n const content = (bytes: Uint8Array): AttachmentContent => ({\n bytes,\n name: displayNameOf(file),\n mimeType: file.mimeType,\n });\n if (file.home.kind === 'page') {\n const annotation = annotationsFor('attachment.download');\n return content(await annotation.downloadResource(file.home.ref, 'file', options));\n }\n refuse(DOWNLOAD, 'attachment.download', options);\n // A file this session is still adding is read once the engine has it.\n if (isPending(file)) await ctx.cancellable(options?.signal, ctx.changes.whenSettled());\n try {\n return content(\n await ctx.cancellable(options?.signal, ctx.doc.attachments.download(file.home.ref)),\n );\n } catch (error) {\n throw toPluginError('attachment', error);\n }\n };\n\n const reveal = (file: AttachedFile): void => {\n if (file.home.kind !== 'page') return;\n const annotation = annotations();\n const record = annotation?.get(file.home.ref);\n if (!annotation || !record) return;\n annotation.selection.set([record.ref]);\n // The file lands a third down the view, as a comment's annotation does.\n ctx.tryGet(StageToken)?.reveal(record.ref.page, {\n rect: record.rect,\n anchor: { x: 'center', y: 0.35 },\n behavior: 'smooth',\n });\n };\n\n const api: AttachmentCapability = {\n list,\n get,\n getSelected,\n select: (files) => ctx.state.update(selected, files.map((file) => file.id)),\n isPending,\n getStatus: files.getStatus,\n ensureLoaded: (options) => ctx.cancellable(options?.signal, files.ensureLoaded()),\n refresh: (options) => ctx.cancellable(options?.signal, files.refresh()),\n\n canDownload: () => ctx.allows(DOWNLOAD),\n canAdd: () => ctx.allows(MODIFY),\n canRemove: (file) =>\n file.home.kind === 'page'\n ? (annotations()?.canDelete(file.home.ref) ?? false)\n : ctx.allows(MODIFY),\n\n add,\n remove,\n download,\n reveal,\n\n onChanged: changed.on,\n onResynced: resynced.on,\n };\n\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { AttachmentToken } from './contract';\nimport { createAttachmentController } from './controller';\nimport { initialAttachmentModel } from './model';\n\n/**\n * The files a document carries. Document-scoped; optionally uses the\n * annotations (a page's files, and removing and saving them) and the stage\n * (going to a page's file).\n */\nexport const attachmentPlugin = () =>\n definePlugin({\n id: 'attachment',\n token: AttachmentToken,\n scope: 'document',\n optional: [AnnotationToken, StageToken],\n state: initialAttachmentModel,\n create: createAttachmentController,\n });\n","/**\n * The attachment page's State table as code: what `useAttachmentState()`\n * returns, and the same fields in every other framework. Reading the state\n * loads the attachments (`ensure`): the first reader of a document starts\n * the read.\n */\nimport { defineState, type ResourceStatus } from '@embedpdf/core';\n\nimport { AttachmentToken, type AttachedFile } from './contract';\n\n/** The document's files, the selected ones, whether they're read, and what this session may do. */\nexport interface AttachmentState {\n /** Every file the document carries: its attachments, then the files of its file attachment annotations. */\n readonly files: readonly AttachedFile[];\n /** The selected files, in the order they were selected. */\n readonly selected: readonly AttachedFile[];\n /** `idle` until something reads the state, then `loading` and `ready`, or `forbidden` or `error`. */\n readonly status: ResourceStatus;\n /** Whether this session may add and remove attachments (`doc.attachments.modify`). */\n readonly canAdd: boolean;\n /** Whether this session may take files out (`doc.download`). */\n readonly canDownload: boolean;\n}\n\nexport const attachmentState = defineState(AttachmentToken, {\n read: (attachment): AttachmentState => ({\n files: attachment.list(),\n selected: attachment.getSelected(),\n status: attachment.getStatus(),\n canAdd: attachment.canAdd(),\n canDownload: attachment.canDownload(),\n }),\n empty: {\n files: [],\n selected: [],\n status: 'idle',\n canAdd: false,\n canDownload: false,\n },\n ensure: (attachment) => attachment.ensureLoaded(),\n});\n"],"mappings":";;;;;;;;;;;AAoBA,MAAa,gCAAiD,EAAE,UAAU,CAAC,EAAE;;AAG7E,SAAgB,SAAS,OAAwB,KAAyC;CACxF,MAAM,SAAS,IAAI,QAAQ,IAAI,MAAM,IAAI,QAAQ,EAAE,MAAM,CAAC;CAG1D,OADE,OAAO,WAAW,MAAM,SAAS,UAAU,OAAO,OAA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Aa,WAAW,YAAY;CACtC;CACA,OAAO;EACL,OAAO,CAAC;EACR,UAAU,CAAC;EACX,QAAQ;EACR,QAAQ;EACR,aAAa;CACf;CACA,SAAS,eAAe,WAAW,aAAa;AAClD,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/model.ts","../src/sync/files.ts","../src/controller.ts","../src/attachment.plugin.ts","../src/state.ts"],"sourcesContent":["/**\n * The attachment model: the document's attachments as the mirror holds\n * them, how an attachment and a page's file become one `AttachedFile`, and\n * the name a new file takes. Pure.\n */\nimport {\n annotationKey,\n type Annotation,\n type AnnotationRef,\n type Attachment,\n type AttachmentRef,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { AttachedFile } from './contract';\n\n/** The session's part: the selected files, by id, in the order they were selected. */\nexport interface AttachmentModel {\n readonly selected: readonly string[];\n}\n\nexport const initialAttachmentModel = (): AttachmentModel => ({ selected: [] });\n\n/** Make these files the selection; the same ids leave the state as it is. */\nexport function selected(state: AttachmentModel, ids: readonly string[]): AttachmentModel {\n const unique = ids.filter((id, i) => ids.indexOf(id) === i);\n const same =\n unique.length === state.selected.length && unique.every((id, i) => id === state.selected[i]);\n return same ? state : { ...state, selected: unique };\n}\n\n/** The document's attachments, in the order its name tree keeps them; `null` before the first read lands. */\nexport type DocumentFiles = readonly Attachment[] | null;\n\n/** An attachment's id: its key. */\nexport const documentFileId = (ref: AttachmentRef): string => `doc:${ref.key}`;\n\n/** A page file's id: its annotation's key. */\nexport const pageFileId = (ref: AnnotationRef): string => `page:${annotationKey(ref)}`;\n\n/** An attachment as the list shows it. */\nexport function documentFileOf(attachment: Attachment): AttachedFile {\n const { ref, index: _index, ...info } = attachment;\n return { ...info, id: documentFileId(ref), home: { kind: 'document', ref } };\n}\n\n/** A file attachment annotation's file as the list shows it; `null` for another kind, or one without a file. */\nexport function pageFileOf(annotation: Annotation): AttachedFile | null {\n if (annotation.subtype !== 'file-attachment' || !annotation.file) return null;\n return {\n ...annotation.file,\n id: pageFileId(annotation.ref),\n home: { kind: 'page', ref: annotation.ref },\n };\n}\n\n/**\n * `name`, or, when a file has it already, the name with the first number\n * that makes it free: `notes (2).txt`, then `notes (3).txt`. The number goes\n * before the extension, as a file manager puts it.\n */\nexport function freeName(name: string, taken: ReadonlySet<string>): string {\n if (!taken.has(name)) return name;\n const dot = name.lastIndexOf('.');\n const stem = dot > 0 ? name.slice(0, dot) : name;\n const extension = dot > 0 ? name.slice(dot) : '';\n for (let number = 2; ; number++) {\n const candidate = `${stem} (${number})${extension}`;\n if (!taken.has(candidate)) return candidate;\n }\n}\n","/**\n * How the document's attachments change: `foldFiles` applies one confirmed\n * event, the mirror's `fold`; `predictFiles` applies one op of a pending\n * change by the engine's rules, the mirror's `predict`; `undoOf` says what\n * undoing ops looks like. Pure.\n */\nimport type { PredictedOp } from '@embedpdf/core';\nimport {\n toAttachmentRef,\n type Attachment,\n type ChangeOp,\n type DocumentEvent,\n} from '@embedpdf/engine-core/runtime';\n\nimport type { DocumentFiles } from '../model';\n\ntype CreateOp = Extract<ChangeOp, { type: 'attachments.create' }>;\n\n/** The files with each `index` its position, keeping the files whose position held. */\nfunction indexed(files: readonly Attachment[]): readonly Attachment[] {\n return files.map((file, index) => (file.index === index ? file : { ...file, index }));\n}\n\nconst has = (files: readonly Attachment[], key: string): boolean =>\n files.some((file) => file.ref.key === key);\n\n/**\n * The files with `attachment` among them, before the first key that sorts\n * after its own, as the name tree puts a new entry; one with its key gives\n * way to it.\n */\nfunction withFile(files: readonly Attachment[], attachment: Attachment): readonly Attachment[] {\n const key = attachment.ref.key;\n const rest = files.filter((file) => file.ref.key !== key);\n const at = rest.findIndex((file) => file.ref.key > key);\n return indexed(\n at < 0 ? [...rest, attachment] : [...rest.slice(0, at), attachment, ...rest.slice(at)],\n );\n}\n\nfunction withoutFile(files: readonly Attachment[], key: string): readonly Attachment[] {\n return has(files, key) ? indexed(files.filter((file) => file.ref.key !== key)) : files;\n}\n\n/* ── confirmed events ────────────────────────────────────────────────────── */\n\n/** One confirmed event, applied with the record it carries. Before the first load there is nothing to apply it to. */\nexport function foldFiles(files: DocumentFiles, event: DocumentEvent): DocumentFiles {\n if (!files) return files;\n switch (event.type) {\n case 'attachments.created':\n case 'attachments.restored':\n return withFile(files, event.attachment);\n case 'attachments.deleted':\n return event.deleted ? withoutFile(files, event.deleted.key) : files;\n default:\n return files;\n }\n}\n\n/* ── pending changes ─────────────────────────────────────────────────────── */\n\n/** A file a create adds, as it shows until the engine answers: what the op says of it, and its size. */\nfunction predictedFile(op: CreateOp): Attachment {\n const bytes = op.resources.file;\n return {\n ref: toAttachmentRef(op.file.name),\n index: 0,\n name: op.file.name,\n mimeType: op.file.mimeType ?? null,\n description: op.file.description ?? null,\n sizeBytes:\n bytes === undefined ? null : bytes instanceof Uint8Array ? bytes.byteLength : bytes.size,\n md5: null,\n createdAt: null,\n modifiedAt: null,\n };\n}\n\n/**\n * One op of a change this session staged, shown before the engine answers,\n * by the engine's rules: a create of a name a file has, a delete of a file\n * that isn't there, and a restore of a name a file has change nothing.\n */\nexport function predictFiles(files: DocumentFiles, op: PredictedOp): DocumentFiles {\n if (!files) return files;\n switch (op.type) {\n case 'attachments.create':\n return has(files, op.file.name) ? files : withFile(files, predictedFile(op));\n case 'attachments.delete':\n return withoutFile(files, op.ref.key);\n case 'attachments.restore':\n return has(files, op.attachment.ref.key) ? files : withFile(files, op.attachment);\n default:\n return files;\n }\n}\n\n/** What undoing one op looks like, read off the files it applies to. */\nfunction undoOfOp(files: readonly Attachment[], op: ChangeOp): PredictedOp[] {\n switch (op.type) {\n case 'attachments.create':\n return [{ type: 'attachments.delete', ref: toAttachmentRef(op.file.name) }];\n case 'attachments.delete': {\n const attachment = files.find((file) => file.ref.key === op.ref.key);\n return attachment ? [{ type: 'attachments.restore', attachment }] : [];\n }\n default:\n return [];\n }\n}\n\n/**\n * What undoing `ops` looks like, read off the files they apply to, each op\n * on the files the ops before it leave; the last op is undone first.\n */\nexport function undoOf(files: DocumentFiles, ops: readonly ChangeOp[]): PredictedOp[] {\n if (!files) return [];\n const undo: PredictedOp[][] = [];\n let current = files;\n for (const op of ops) {\n undo.push(undoOfOp(current, op));\n current = predictFiles(current, op) ?? current;\n }\n return undo.reverse().flat();\n}\n","import {\n memo,\n PluginError,\n toPluginError,\n type DocCapability,\n type OperationOptions,\n type PendingChange,\n type PluginContext,\n} from '@embedpdf/core';\nimport type {\n Annotation,\n Attachment,\n AttachmentContent,\n AttachmentFileSource,\n ChangeItem,\n ChangeOp,\n ChangeResult,\n DocumentEvent,\n} from '@embedpdf/engine-core/runtime';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport type {\n AttachedFile,\n AttachmentCapability,\n AttachmentsChangedEvent,\n AttachmentsResyncedEvent,\n} from './contract';\nimport {\n documentFileOf,\n freeName,\n pageFileOf,\n selected,\n type AttachmentModel,\n type DocumentFiles,\n} from './model';\nimport { displayNameOf } from './names';\nimport { foldFiles, predictFiles, undoOf } from './sync/files';\n\nconst MODIFY: DocCapability = 'doc.attachments.modify';\nconst DOWNLOAD: DocCapability = 'doc.download';\n\nconst NO_FILES: readonly AttachedFile[] = Object.freeze([]);\n\n/**\n * The attachments controller. The document's attachments are a mirror,\n * read when something asks for them (`ensureLoaded()`, what\n * `attachmentState` does), and every read shows its `view()`: the engine's\n * attachments with this session's pending adds and removes on top. A page's\n * file is a file attachment annotation, read from the annotation plugin, so\n * the list shows both homes with no read of its own. Each add or remove of\n * an attachment is one change on the document's queue: it shows at once, is\n * one step of the history, and undoing it shows the files as they were.\n */\nexport function createAttachmentController(ctx: PluginContext<AttachmentModel>) {\n const changed = ctx.events.source<AttachmentsChangedEvent>();\n const resynced = ctx.events.source<AttachmentsResyncedEvent>();\n\n // One `AttachedFile` per record, so a list row keeps its object while its file is unchanged.\n const documentFiles = new WeakMap<Attachment, AttachedFile>();\n const fileOfAttachment = (attachment: Attachment): AttachedFile => {\n let file = documentFiles.get(attachment);\n if (!file) documentFiles.set(attachment, (file = documentFileOf(attachment)));\n return file;\n };\n const pageFiles = new WeakMap<Annotation, AttachedFile | null>();\n const fileOfAnnotation = (annotation: Annotation): AttachedFile | null => {\n let file = pageFiles.get(annotation);\n if (file === undefined) pageFiles.set(annotation, (file = pageFileOf(annotation)));\n return file;\n };\n\n /** The fact a confirmed attachment event reports, or `null` for any other event. */\n const factOf = (\n event: DocumentEvent,\n previous: DocumentFiles,\n ): Omit<AttachmentsChangedEvent, 'origin'> | null => {\n switch (event.type) {\n case 'attachments.created':\n return { type: 'created', files: [fileOfAttachment(event.attachment)] };\n case 'attachments.restored':\n return { type: 'restored', files: [fileOfAttachment(event.attachment)] };\n case 'attachments.deleted': {\n const gone = previous?.find((file) => file.ref.key === event.deleted?.key);\n return { type: 'deleted', files: gone ? [fileOfAttachment(gone)] : [] };\n }\n default:\n return null;\n }\n };\n\n const files = ctx.mirror<DocumentFiles>({\n name: 'attachments',\n onDemand: true,\n initial: () => null,\n load: async (doc) => ({ value: (await doc.attachments.list()).attachments }),\n fold: foldFiles,\n predict: predictFiles,\n onChanged: ({ cause, event, previous, next }) => {\n if (!next) return;\n if (cause === 'load') {\n resynced.emit({ files: next.map(fileOfAttachment) });\n return;\n }\n const fact = event && 'origin' in event ? factOf(event, previous) : null;\n if (fact && event && 'origin' in event) changed.emit({ ...fact, origin: event.origin });\n },\n });\n\n const annotations = () => ctx.tryGet(AnnotationToken);\n\n /* ── reads ─────────────────────────────────────────────────────────────── */\n\n const list = memo(\n () => [files.view(), annotations()?.list() ?? null] as const,\n (attachments, annots) => {\n const all = [\n ...(attachments ?? []).map(fileOfAttachment),\n ...(annots ?? []).flatMap((annotation) => {\n const file = fileOfAnnotation(annotation);\n return file ? [file] : [];\n }),\n ];\n return all.length > 0 ? all : NO_FILES;\n },\n );\n const get = (id: string): AttachedFile | null => list().find((file) => file.id === id) ?? null;\n const getSelected = memo(\n () => [list(), ctx.state.get().selected] as const,\n (files, ids) => {\n if (ids.length === 0) return NO_FILES;\n const byId = new Map(files.map((file) => [file.id, file]));\n const chosen = ids.flatMap((id) => {\n const file = byId.get(id);\n return file ? [file] : [];\n });\n return chosen.length > 0 ? chosen : NO_FILES;\n },\n );\n\n const isPending = (file: AttachedFile): boolean => {\n if (file.home.kind === 'page') return annotations()?.isPending(file.home.ref) ?? false;\n const key = file.home.ref.key;\n return !(files.get() ?? []).some((confirmed) => confirmed.ref.key === key);\n };\n\n /* ── writes ────────────────────────────────────────────────────────────── */\n\n /** Refuse before anything starts: without the permission, or once the caller cancelled. */\n const refuse = (permission: DocCapability, operation: string, options?: OperationOptions) => {\n ctx.assertAllowed(permission, operation);\n if (options?.signal?.aborted) {\n throw new PluginError('operation-cancelled', 'attachment', `${operation} was cancelled`);\n }\n };\n\n /** The engine's answer to a staged change. */\n const answer = async (\n change: PendingChange,\n options?: OperationOptions,\n ): Promise<ChangeResult> => {\n try {\n return await ctx.cancellable(options?.signal, change.result);\n } catch (error) {\n throw toPluginError('attachment', error);\n }\n };\n\n /** The annotation plugin, for a page's file: the list shows none without it. */\n const annotationsFor = (operation: string) => {\n const annotation = annotations();\n if (!annotation) {\n throw new PluginError('not-found', 'attachment', `${operation}: no annotation plugin`);\n }\n return annotation;\n };\n\n /** The op that attaches `source` under a name no file has (`taken`, which it joins). */\n const createOp = (source: AttachmentFileSource, taken: Set<string>): ChangeOp => {\n const { data, description } = source;\n const blob = typeof Blob !== 'undefined' && data instanceof Blob ? data : null;\n const given = source.name ?? (blob && 'name' in blob ? String(blob.name) : '');\n if (!given) {\n throw new PluginError(\n 'invalid-input',\n 'attachment',\n 'attachment.add: a file needs a name: pass { data, name } or a File',\n );\n }\n const name = freeName(given, taken);\n taken.add(name);\n const mimeType = source.mimeType ?? (blob?.type || undefined);\n return {\n type: 'attachments.create',\n file: {\n name,\n ...(mimeType !== undefined ? { mimeType } : {}),\n ...(description !== undefined ? { description } : {}),\n },\n resources: { file: data instanceof ArrayBuffer ? new Uint8Array(data) : data },\n };\n };\n\n const create: AttachmentCapability['create'] = async (sources, options) => {\n refuse(MODIFY, 'attachment.add', options);\n if (sources.length === 0) return NO_FILES;\n // The names in the document decide the free ones, so they are read first.\n await ctx.cancellable(options?.signal, files.ensureLoaded());\n const taken = new Set((files.view() ?? []).map((file) => file.ref.key));\n const ops = sources.map((source) => createOp(source, taken));\n const change = ctx.changes.stage({\n label: { key: 'attachment.add', count: ops.length },\n ops,\n undo: undoOf(files.view(), ops),\n });\n const result = await answer(change, options);\n return result.items.flatMap((item: ChangeItem) =>\n item.type === 'attachments.create' ? [fileOfAttachment(item.attachment)] : [],\n );\n };\n\n const remove: AttachmentCapability['delete'] = async (file, options) => {\n if (file.home.kind === 'page') {\n return annotationsFor('attachment.remove').delete(file.home.ref, options);\n }\n refuse(MODIFY, 'attachment.remove', options);\n const { ref } = file.home;\n const view = files.view();\n if (view && !view.some((attachment) => attachment.ref.key === ref.key)) {\n throw new PluginError(\n 'not-found',\n 'attachment',\n `attachment.remove: the document has no attachment '${ref.key}'`,\n );\n }\n const ops: ChangeOp[] = [{ type: 'attachments.delete', ref }];\n const change = ctx.changes.stage({\n label: { key: 'attachment.remove' },\n ops,\n undo: undoOf(view, ops),\n });\n await answer(change, options);\n };\n\n const download: AttachmentCapability['download'] = async (file, options) => {\n const content = (bytes: Uint8Array): AttachmentContent => ({\n bytes,\n name: displayNameOf(file),\n mimeType: file.mimeType,\n });\n if (file.home.kind === 'page') {\n const annotation = annotationsFor('attachment.download');\n return content(await annotation.downloadResource(file.home.ref, 'file', options));\n }\n refuse(DOWNLOAD, 'attachment.download', options);\n // A file this session is still adding is read once the engine has it.\n if (isPending(file)) await ctx.cancellable(options?.signal, ctx.changes.whenSettled());\n try {\n return content(\n await ctx.cancellable(options?.signal, ctx.doc.attachments.download(file.home.ref)),\n );\n } catch (error) {\n throw toPluginError('attachment', error);\n }\n };\n\n const reveal = (file: AttachedFile): void => {\n if (file.home.kind !== 'page') return;\n const annotation = annotations();\n const record = annotation?.get(file.home.ref);\n if (!annotation || !record) return;\n annotation.selection.select([record.ref]);\n // The file lands a third down the view, as a comment's annotation does.\n ctx.tryGet(StageToken)?.reveal(record.ref.page, {\n rect: record.rect,\n align: { x: 'center', y: 0.35 },\n behavior: 'smooth',\n });\n };\n\n const api: AttachmentCapability = {\n list,\n get,\n getSelected,\n select: (files) =>\n ctx.state.update(\n selected,\n files.map((file) => file.id),\n ),\n isPending,\n getStatus: files.getStatus,\n ensureLoaded: (options) => ctx.cancellable(options?.signal, files.ensureLoaded()),\n refresh: (options) => ctx.cancellable(options?.signal, files.refresh()),\n\n canDownload: () => ctx.allows(DOWNLOAD),\n canCreate: () => ctx.allows(MODIFY),\n canDelete: (file) =>\n file.home.kind === 'page'\n ? (annotations()?.canDelete(file.home.ref) ?? false)\n : ctx.allows(MODIFY),\n\n create,\n delete: remove,\n download,\n reveal,\n\n onChanged: changed.on,\n onResynced: resynced.on,\n };\n\n return { api };\n}\n","import { definePlugin } from '@embedpdf/core';\nimport { AnnotationToken } from '@embedpdf/plugin-annotation/contract';\nimport { StageToken } from '@embedpdf/plugin-stage/contract';\n\nimport { AttachmentToken } from './contract';\nimport { createAttachmentController } from './controller';\nimport { initialAttachmentModel } from './model';\n\n/**\n * The files a document carries. Document-scoped; optionally uses the\n * annotations (a page's files, and removing and saving them) and the stage\n * (going to a page's file).\n */\nexport const attachmentPlugin = () =>\n definePlugin({\n id: 'attachment',\n token: AttachmentToken,\n scope: 'document',\n optional: [AnnotationToken, StageToken],\n state: initialAttachmentModel,\n create: createAttachmentController,\n });\n","/**\n * The attachment page's State table as code: what `useAttachmentState()`\n * returns, and the same fields in every other framework. Reading the state\n * loads the attachments (`ensure`): the first reader of a document starts\n * the read.\n */\nimport { defineState, type ResourceStatus } from '@embedpdf/core';\n\nimport { AttachmentToken, type AttachedFile } from './contract';\n\n/** The document's files, the selected ones, whether they're read, and what this session may do. */\nexport interface AttachmentState {\n /** Every file the document carries: its attachments, then the files of its file attachment annotations. */\n readonly files: readonly AttachedFile[];\n /** The selected files, in the order they were selected. */\n readonly selected: readonly AttachedFile[];\n /** `idle` until something reads the state, then `loading` and `ready`, or `forbidden` or `error`. */\n readonly status: ResourceStatus;\n /** Whether this session may add and remove attachments (`doc.attachments.modify`). */\n readonly canCreate: boolean;\n /** Whether this session may take files out (`doc.download`). */\n readonly canDownload: boolean;\n}\n\nexport const attachmentState = defineState(AttachmentToken, {\n read: (attachment): AttachmentState => ({\n files: attachment.list(),\n selected: attachment.getSelected(),\n status: attachment.getStatus(),\n canCreate: attachment.canCreate(),\n canDownload: attachment.canDownload(),\n }),\n empty: {\n files: [],\n selected: [],\n status: 'idle',\n canCreate: false,\n canDownload: false,\n },\n ensure: (attachment) => attachment.ensureLoaded(),\n});\n"],"mappings":";;;;;;;;;;;AAoBA,MAAa,gCAAiD,EAAE,UAAU,CAAC,EAAE;;AAG7E,SAAgB,SAAS,OAAwB,KAAyC;CACxF,MAAM,SAAS,IAAI,QAAQ,IAAI,MAAM,IAAI,QAAQ,EAAE,MAAM,CAAC;CAG1D,OADE,OAAO,WAAW,MAAM,SAAS,UAAU,OAAO,OAAO,IAAI,MAAM,OAAO,MAAM,SAAS,EAAE,IAC/E,QAAQ;EAAE,GAAG;EAAO,UAAU;CAAO;AACrD;;AAMA,MAAa,kBAAkB,QAA+B,OAAO,IAAI;;AAGzE,MAAa,cAAc,QAA+B,QAAQ,cAAc,GAAG;;AAGnF,SAAgB,eAAe,YAAsC;CACnE,MAAM,EAAE,KAAK,OAAO,QAAQ,GAAG,SAAS;CACxC,OAAO;EAAE,GAAG;EAAM,IAAI,eAAe,GAAG;EAAG,MAAM;GAAE,MAAM;GAAY;EAAI;CAAE;AAC7E;;AAGA,SAAgB,WAAW,YAA6C;CACtE,IAAI,WAAW,YAAY,qBAAqB,CAAC,WAAW,MAAM,OAAO;CACzE,OAAO;EACL,GAAG,WAAW;EACd,IAAI,WAAW,WAAW,GAAG;EAC7B,MAAM;GAAE,MAAM;GAAQ,KAAK,WAAW;EAAI;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,YAAY,IAAI,YAAY,SAAS,QAAQ,MAAM,aAAa,CAAC;EAChF,UAAU,YAAY,IAAI,YAAY,SAAS,QAAQ,MAAM,QAAQ,CAAC;EAEtE,mBAAmB,IAAI,OAAO,QAAQ;EACtC,iBAAiB,IAAI,OAAO,MAAM;EAClC,YAAY,SACV,KAAK,KAAK,SAAS,SACd,YAAY,CAAC,EAAE,UAAU,KAAK,KAAK,GAAG,KAAK,QAC5C,IAAI,OAAO,MAAM;EAEvB;EACA,QAAQ;EACR;EACA;EAEA,WAAW,QAAQ;EACnB,YAAY,SAAS;CAGZ,EAAE;AACf;;;;;;;;AC1SA,MAAa,yBACX,aAAa;CACX,IAAI;CACJ,OAAO;CACP,OAAO;CACP,UAAU,CAAC,iBAAiB,UAAU;CACtC,OAAO;CACP,QAAQ;AACV,CAAC;;;;;;;;;ACGH,MAAa,kBAAkB,YAAY,iBAAiB;CAC1D,OAAO,gBAAiC;EACtC,OAAO,WAAW,KAAK;EACvB,UAAU,WAAW,YAAY;EACjC,QAAQ,WAAW,UAAU;EAC7B,WAAW,WAAW,UAAU;EAChC,aAAa,WAAW,YAAY;CACtC;CACA,OAAO;EACL,OAAO,CAAC;EACR,UAAU,CAAC;EACX,QAAQ;EACR,WAAW;EACX,aAAa;CACf;CACA,SAAS,eAAe,WAAW,aAAa;AAClD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@embedpdf/plugin-attachment",
3
- "version": "3.0.0-next.22",
3
+ "version": "3.0.0-next.23",
4
4
  "private": false,
5
5
  "description": "Document-scoped attachments: the files a document carries, in its attachments and in file attachment annotations, as one list with this session's pending adds and removes shown; adding and removing them as undoable changes, downloading them, and going to a page's file.",
6
6
  "type": "module",
@@ -22,18 +22,18 @@
22
22
  "dist"
23
23
  ],
24
24
  "dependencies": {
25
- "@embedpdf/core": "3.0.0-next.22",
26
- "@embedpdf/plugin-annotation": "3.0.0-next.22",
27
- "@embedpdf/plugin-stage": "3.0.0-next.22",
28
- "@embedpdf/engine-core": "3.0.0-next.22"
25
+ "@embedpdf/core": "3.0.0-next.23",
26
+ "@embedpdf/engine-core": "3.0.0-next.23",
27
+ "@embedpdf/plugin-stage": "3.0.0-next.23",
28
+ "@embedpdf/plugin-annotation": "3.0.0-next.23"
29
29
  },
30
30
  "devDependencies": {
31
31
  "typescript": "^5.0.0",
32
32
  "vitest": "^2.1.9",
33
33
  "@embedpdf/tooling-build": "0.0.0",
34
- "@embedpdf/engine": "3.0.0-next.22",
35
- "@embedpdf/plugin-history": "3.0.0-next.22",
36
- "@embedpdf/plugin-interaction": "3.0.0-next.22"
34
+ "@embedpdf/engine": "3.0.0-next.23",
35
+ "@embedpdf/plugin-history": "3.0.0-next.23",
36
+ "@embedpdf/plugin-interaction": "3.0.0-next.23"
37
37
  },
38
38
  "license": "Apache-2.0",
39
39
  "sideEffects": false,
@@ -1 +0,0 @@
1
- {"version":3,"file":"contract-C__XpO5g.cjs","names":[],"sources":["../src/token.ts","../src/names.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { AttachmentCapability } from './contract';\n\nexport const AttachmentToken = createCapabilityToken<AttachmentCapability>('attachment', {\n hint: \"add attachmentPlugin() from '@embedpdf/plugin-attachment' to your plugins list\",\n // Without a document, an adapter's stand-in rejects these with `not-ready`, as the\n // capability would; the type asks for every member that returns a promise.\n promises: {\n ensureLoaded: true,\n refresh: true,\n add: true,\n remove: true,\n download: true,\n },\n});\n","/**\n * Control characters, and the bidi controls a name can use to look like\n * another: with a right-to-left override (U+202E) where `[RLO]` stands,\n * `invoice[RLO]fdp.exe` shows as `invoiceexe.pdf`.\n */\n// eslint-disable-next-line no-control-regex -- finding control characters is its job\nconst HIDDEN = /[\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g;\n\n/**\n * A file's name as a person may see it and save it: without control\n * characters and bidi controls, trimmed. `attachment` when nothing is left.\n */\nexport function displayNameOf(file: { readonly name: string }): string {\n return file.name.replace(HIDDEN, '').trim() || 'attachment';\n}\n"],"mappings":";;AAKA,MAAa,mBAAA,2BAAA,CAAA,CAAA,sBAAA,CAA8D,cAAc;CACvF,MAAM;CAGN,UAAU;EACR,cAAc;EACd,SAAS;EACT,KAAK;EACL,QAAQ;EACR,UAAU;CACZ;AACF,CAAC;;;;;;;;ACVD,MAAM,SAAS;;;;;AAMf,SAAgB,cAAc,MAAyC;CACrE,OAAO,KAAK,KAAK,QAAQ,QAAQ,EAAE,CAAC,CAAC,KAAK,KAAK;AACjD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"contract-CqFkPaxs.js","names":[],"sources":["../src/token.ts","../src/names.ts"],"sourcesContent":["/** The package token, created once here; `contract.ts` re-exports it. */\nimport { createCapabilityToken } from '@embedpdf/core';\n\nimport type { AttachmentCapability } from './contract';\n\nexport const AttachmentToken = createCapabilityToken<AttachmentCapability>('attachment', {\n hint: \"add attachmentPlugin() from '@embedpdf/plugin-attachment' to your plugins list\",\n // Without a document, an adapter's stand-in rejects these with `not-ready`, as the\n // capability would; the type asks for every member that returns a promise.\n promises: {\n ensureLoaded: true,\n refresh: true,\n add: true,\n remove: true,\n download: true,\n },\n});\n","/**\n * Control characters, and the bidi controls a name can use to look like\n * another: with a right-to-left override (U+202E) where `[RLO]` stands,\n * `invoice[RLO]fdp.exe` shows as `invoiceexe.pdf`.\n */\n// eslint-disable-next-line no-control-regex -- finding control characters is its job\nconst HIDDEN = /[\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g;\n\n/**\n * A file's name as a person may see it and save it: without control\n * characters and bidi controls, trimmed. `attachment` when nothing is left.\n */\nexport function displayNameOf(file: { readonly name: string }): string {\n return file.name.replace(HIDDEN, '').trim() || 'attachment';\n}\n"],"mappings":";;;AAKA,MAAa,kBAAkB,sBAA4C,cAAc;CACvF,MAAM;CAGN,UAAU;EACR,cAAc;EACd,SAAS;EACT,KAAK;EACL,QAAQ;EACR,UAAU;CACZ;AACF,CAAC;;;;;;;;ACVD,MAAM,SAAS;;;;;AAMf,SAAgB,cAAc,MAAyC;CACrE,OAAO,KAAK,KAAK,QAAQ,QAAQ,EAAE,CAAC,CAAC,KAAK,KAAK;AACjD"}