@embedpdf/plugin-stamp 3.0.0-next.2 → 3.0.0-next.20
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.
- package/dist/contract-BQP56Vp4.d.cts +449 -0
- package/dist/contract-D6Hs6iO3.d.ts +449 -0
- package/dist/contract-DHcn38S9.js +87 -0
- package/dist/contract-DHcn38S9.js.map +1 -0
- package/dist/contract-Dj5KiMyW.cjs +157 -0
- package/dist/contract-Dj5KiMyW.cjs.map +1 -0
- package/dist/contract.cjs +5 -0
- package/dist/contract.d.cts +2 -0
- package/dist/contract.d.ts +2 -0
- package/dist/contract.js +2 -0
- package/dist/index.cjs +1403 -474
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -179
- package/dist/index.d.ts +21 -179
- package/dist/index.js +1398 -475
- package/dist/index.js.map +1 -1
- package/package.json +15 -8
package/dist/index.js
CHANGED
|
@@ -1,16 +1,746 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const
|
|
1
|
+
import { a as assetIdFor, c as parseStampKey, d as stampPieceInfo, f as StampToken, i as STAMP_PIECEINFO_APP, l as stampKey, n as DEFAULT_LIBRARY_KIND, o as customStampName, r as STAMP_LIBRARY_PIECEINFO_APP, s as libraryKindFromPdfName, t as STAMP_DEFAULTS, u as stampLibraryPieceInfo } from "./contract-DHcn38S9.js";
|
|
2
|
+
import { DocumentsToken, PluginError, composeApi, definePlugin, defineState, toPluginError, toPluginErrorInfo } from "@embedpdf/core";
|
|
3
|
+
import { ActionsToken } from "@embedpdf/plugin-actions/contract";
|
|
4
|
+
import { AnnotationToken } from "@embedpdf/plugin-annotation/contract";
|
|
5
|
+
import { formEffectOps, isLocalEngine, resolveBinarySource, sniffBinaryMetadata } from "@embedpdf/engine-core/runtime";
|
|
6
|
+
import { javaScriptProgramFromActionTree } from "@embedpdf/core-acrojs";
|
|
7
|
+
import { ActionsToken as ActionsToken$1 } from "@embedpdf/plugin-actions/contract/host";
|
|
8
|
+
import { AnnotationToken as AnnotationToken$1 } from "@embedpdf/plugin-annotation/contract/host";
|
|
9
|
+
import { createFormScriptingController } from "@embedpdf/plugin-form/scripting";
|
|
10
|
+
//#region src/services/errors.ts
|
|
11
|
+
/** A `PluginError` raised by the stamp plugin. */
|
|
12
|
+
const stampError = (code, message) => new PluginError(code, "stamp", message);
|
|
13
|
+
const notFound = (what, id) => stampError("not-found", `unknown ${what} '${id}'`);
|
|
14
|
+
/**
|
|
15
|
+
* A refusal that names the missing permission. The stamp plugin acts on a
|
|
16
|
+
* document it isn't bound to, so it asks that document's checks instead of
|
|
17
|
+
* `ctx.assertAllowed`, and refuses with the same error.
|
|
18
|
+
*/
|
|
19
|
+
const permissionDenied = (permission, operation) => new PluginError("permission-denied", "stamp", `${operation} requires ${permission}`, { permission });
|
|
20
|
+
/** Stop before the next step, or before anything is kept, once the caller cancelled. */
|
|
21
|
+
const throwIfCancelled = (signal) => {
|
|
22
|
+
if (signal?.aborted) throw new PluginError("operation-cancelled", "stamp", "operation cancelled", { cause: signal.reason });
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* A capability verb: whatever the asset engine, a sibling plugin or a binary
|
|
26
|
+
* source rejects with reaches the caller as a `PluginError`.
|
|
27
|
+
*/
|
|
28
|
+
const verb = (run) => async (...args) => {
|
|
29
|
+
try {
|
|
30
|
+
return await run(...args);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
throw toPluginError("stamp", error);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region src/read/catalog.ts
|
|
37
|
+
/** Reads over the state and the binaries resource: libraries, assets,
|
|
38
|
+
* previews, the library's PDF, and the checks. */
|
|
39
|
+
function createCatalog(ctx, { binaries, assetEngine, ghosts, targets }) {
|
|
40
|
+
const { binaries: assetBinaries, libraryBinaries } = binaries;
|
|
41
|
+
const { ghostProvider } = ghosts;
|
|
42
|
+
const { documentIdOf } = targets;
|
|
43
|
+
const listAssets = (filter) => {
|
|
44
|
+
const state = ctx.state.get();
|
|
45
|
+
return (filter?.libraryId ? [filter.libraryId] : state.libraryOrder).flatMap((libraryId) => (state.libraries[libraryId]?.assetIds ?? []).map((id) => state.assets[id])).filter((asset) => asset != null && (!filter?.kind || asset.kind === filter.kind) && (!filter?.category || (asset.categories ?? []).includes(filter.category)));
|
|
46
|
+
};
|
|
47
|
+
/** Placing is annotation work: the document's annotation plugin answers. */
|
|
48
|
+
const canPlace = (documentId) => {
|
|
49
|
+
const id = documentIdOf(documentId);
|
|
50
|
+
if (!id) return false;
|
|
51
|
+
return ctx.tryForDocument(AnnotationToken, id)?.canCreate() ?? false;
|
|
52
|
+
};
|
|
53
|
+
/** A stamp made from annotations copies them out of the document, as a download does. */
|
|
54
|
+
const canCreateFromAnnotations = (documentId) => {
|
|
55
|
+
const id = documentIdOf(documentId);
|
|
56
|
+
return id !== null && ctx.get(DocumentsToken).canDownload(id);
|
|
57
|
+
};
|
|
58
|
+
return {
|
|
59
|
+
canPlace,
|
|
60
|
+
canCreateFromAnnotations,
|
|
61
|
+
api: {
|
|
62
|
+
listLibraries: (filter) => {
|
|
63
|
+
const state = ctx.state.get();
|
|
64
|
+
const kinds = filter?.kind === void 0 ? null : new Set(typeof filter.kind === "string" ? [filter.kind] : filter.kind);
|
|
65
|
+
return state.libraryOrder.map((id) => state.libraries[id]).filter((library) => library != null && (kinds === null || kinds.has(library.kind)));
|
|
66
|
+
},
|
|
67
|
+
getLibrary: (libraryId) => ctx.state.get().libraries[libraryId] ?? null,
|
|
68
|
+
listAssets,
|
|
69
|
+
getAsset: (assetId) => ctx.state.get().assets[assetId] ?? null,
|
|
70
|
+
getAssetPreview: (assetId) => assetBinaries.get(assetId)?.preview ?? null,
|
|
71
|
+
renderAssetPreview: verb(async (assetId, { width, signal }) => {
|
|
72
|
+
throwIfCancelled(signal);
|
|
73
|
+
const binary = assetBinaries.get(assetId);
|
|
74
|
+
if (!binary) throw notFound("asset", assetId);
|
|
75
|
+
const preview = await ctx.cancellable(signal, ghostProvider(binary.bytes, binary.preview, assetId)(width));
|
|
76
|
+
return preview ? {
|
|
77
|
+
bytes: preview.bytes,
|
|
78
|
+
mimeType: preview.mimeType ?? "image/png"
|
|
79
|
+
} : null;
|
|
80
|
+
}),
|
|
81
|
+
readAssetBytes: (assetId) => {
|
|
82
|
+
const bytes = assetBinaries.get(assetId)?.bytes;
|
|
83
|
+
return bytes ? new Uint8Array(bytes) : null;
|
|
84
|
+
},
|
|
85
|
+
exportLibrary: async (libraryId, options) => {
|
|
86
|
+
throwIfCancelled(options?.signal);
|
|
87
|
+
const bytes = libraryBinaries.get(libraryId);
|
|
88
|
+
if (!bytes) throw notFound("library", libraryId);
|
|
89
|
+
return new Uint8Array(bytes);
|
|
90
|
+
},
|
|
91
|
+
canPlace,
|
|
92
|
+
canCreateFromAnnotations,
|
|
93
|
+
canImport: assetEngine.canImport
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
//#endregion
|
|
98
|
+
//#region src/services/asset-engine.ts
|
|
99
|
+
/**
|
|
100
|
+
* The asset engine port and the canonical-library services every write
|
|
101
|
+
* needs: opening library bytes as a document on a local engine, import-time
|
|
102
|
+
* previews, and the import-support fact learned from the first import.
|
|
103
|
+
*/
|
|
104
|
+
/** Session-unique ids (scratch documents, library ids a file does not carry):
|
|
105
|
+
* a timestamp plus a counter. */
|
|
106
|
+
let idCounter = 0;
|
|
107
|
+
const uid = (prefix) => `${prefix}-${Date.now().toString(36)}-${(idCounter++).toString(36)}`;
|
|
108
|
+
function createAssetEngine(ctx) {
|
|
109
|
+
const settings = ctx.settings();
|
|
110
|
+
/** Set once an import finds the asset engine is not local (cloud). */
|
|
111
|
+
let importSupported = null;
|
|
112
|
+
let resolved = null;
|
|
113
|
+
/** Engines this plugin made through a configured function: destroyed with it. */
|
|
114
|
+
const owned = [];
|
|
115
|
+
const assetEngine = () => {
|
|
116
|
+
const configured = settings.get().assetEngine;
|
|
117
|
+
if (resolved?.from !== configured) {
|
|
118
|
+
const engine = !configured ? ctx.engine : typeof configured === "function" ? configured() : configured;
|
|
119
|
+
if (typeof configured === "function") owned.push(engine);
|
|
120
|
+
resolved = {
|
|
121
|
+
from: configured,
|
|
122
|
+
engine
|
|
123
|
+
};
|
|
124
|
+
importSupported = null;
|
|
125
|
+
}
|
|
126
|
+
return resolved.engine;
|
|
127
|
+
};
|
|
128
|
+
/** Each asset engine's fonts, by key: each read and registered once (a failed read is tried again). */
|
|
129
|
+
const registered = /* @__PURE__ */ new WeakMap();
|
|
130
|
+
/**
|
|
131
|
+
* Register the font a typed mark names on the asset engine, when it's one of the `fonts`
|
|
132
|
+
* setting's: a standard font, or one the engine has, needs nothing.
|
|
133
|
+
*/
|
|
134
|
+
const registerFont = async (key) => {
|
|
135
|
+
const font = settings.get().fonts.find((each) => each.key === key);
|
|
136
|
+
if (!font) return;
|
|
137
|
+
const engine = await assetEngine();
|
|
138
|
+
if (!isLocalEngine(engine)) return;
|
|
139
|
+
let byKey = registered.get(engine);
|
|
140
|
+
if (!byKey) registered.set(engine, byKey = /* @__PURE__ */ new Map());
|
|
141
|
+
let registering = byKey.get(key);
|
|
142
|
+
if (!registering) {
|
|
143
|
+
const fonts = byKey;
|
|
144
|
+
registering = font.load().then((data) => engine.fonts.register({
|
|
145
|
+
key,
|
|
146
|
+
data
|
|
147
|
+
})).then(() => void 0);
|
|
148
|
+
fonts.set(key, registering);
|
|
149
|
+
registering.catch(() => fonts.delete(key));
|
|
150
|
+
}
|
|
151
|
+
return registering;
|
|
152
|
+
};
|
|
153
|
+
/** Library PDFs are sliced and tagged (`/PieceInfo`) on a local engine only. */
|
|
154
|
+
const openAssetDocument = async (bytes) => {
|
|
155
|
+
const engine = await assetEngine();
|
|
156
|
+
if (!isLocalEngine(engine)) {
|
|
157
|
+
if (importSupported !== false) {
|
|
158
|
+
importSupported = false;
|
|
159
|
+
ctx.notify();
|
|
160
|
+
}
|
|
161
|
+
throw stampError("unsupported", settings.get().assetEngine ? "the stamp plugin's assetEngine must be a local engine (createLocalEngine())" : "importing a library PDF needs a local engine, and this viewer's engine is a cloud engine. Pass stampPlugin({ assetEngine: () => import('@embedpdf/engine').then((module) => module.createLocalEngine()) }): it loads lazily, on first import.");
|
|
162
|
+
}
|
|
163
|
+
return engine.open({
|
|
164
|
+
kind: "bytes",
|
|
165
|
+
id: uid("stamp-import"),
|
|
166
|
+
bytes
|
|
167
|
+
}, { scope: ["*"] });
|
|
168
|
+
};
|
|
169
|
+
/** Import-time preview render to bytes. The asset engine is local by
|
|
170
|
+
* definition, so the image source is always inline bytes. */
|
|
171
|
+
const imageToPreview = (image) => {
|
|
172
|
+
if (image.source.kind !== "bytes") throw stampError("unsupported", "the asset engine returned a URL-sourced render; asset engines must be local");
|
|
173
|
+
return {
|
|
174
|
+
bytes: image.source.bytes,
|
|
175
|
+
mimeType: image.contentType
|
|
176
|
+
};
|
|
177
|
+
};
|
|
178
|
+
/** Thumbnail render of one library page (the small picker image). */
|
|
179
|
+
const renderThumbnail = async (handle) => imageToPreview(await handle.render.image({
|
|
180
|
+
viewport: {
|
|
181
|
+
kind: "width",
|
|
182
|
+
width: settings.get().previewWidth
|
|
183
|
+
},
|
|
184
|
+
background: "transparent",
|
|
185
|
+
includeAnnotations: true,
|
|
186
|
+
format: "png"
|
|
187
|
+
}));
|
|
188
|
+
ctx.cleanup(() => {
|
|
189
|
+
resolved = null;
|
|
190
|
+
for (const engine of owned.splice(0)) Promise.resolve(engine).then((made) => made.destroy()).catch(() => {});
|
|
191
|
+
});
|
|
192
|
+
return {
|
|
193
|
+
openAssetDocument,
|
|
194
|
+
registerFont,
|
|
195
|
+
imageToPreview,
|
|
196
|
+
renderThumbnail,
|
|
197
|
+
/** Optimistic until an import finds the asset engine is not local (cloud). */
|
|
198
|
+
canImport: () => {
|
|
199
|
+
if (resolved && resolved.from !== settings.get().assetEngine) return true;
|
|
200
|
+
return importSupported !== false;
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
//#endregion
|
|
205
|
+
//#region src/services/binaries.ts
|
|
206
|
+
function createBinaries(ctx) {
|
|
207
|
+
/** Asset bytes (a one-page placement PDF) and the cached preview, by asset id. */
|
|
208
|
+
const binaries = /* @__PURE__ */ new Map();
|
|
209
|
+
/** The durable source of truth for a canonical library. Asset PDFs above
|
|
210
|
+
* are derived page extractions; this map owns the rewritten whole PDF. */
|
|
211
|
+
const libraryBinaries = /* @__PURE__ */ new Map();
|
|
212
|
+
/** Whole-PDF rewrites are serialized per library, or two concurrent
|
|
213
|
+
* appends could both start from the same bytes and lose one page. A
|
|
214
|
+
* mutation whose signal fired while it waited never starts. */
|
|
215
|
+
const mutateLibrary = (libraryId, mutation, signal) => ctx.serialQueue(`library:${libraryId}`)(mutation, { signal });
|
|
216
|
+
/**
|
|
217
|
+
* Ghost renders, one per size bucket per asset, rendered lazily on the
|
|
218
|
+
* asset engine the first time the ghost is shown at that size and kept
|
|
219
|
+
* until the asset goes away. Materialized (dynamic) placements are
|
|
220
|
+
* user/time specific and cache only for their own arm (`cacheKey` null).
|
|
221
|
+
*/
|
|
222
|
+
const ghostRenders = /* @__PURE__ */ new Map();
|
|
223
|
+
ctx.cleanup(() => {
|
|
224
|
+
binaries.clear();
|
|
225
|
+
ghostRenders.clear();
|
|
226
|
+
libraryBinaries.clear();
|
|
227
|
+
});
|
|
228
|
+
return {
|
|
229
|
+
binaries,
|
|
230
|
+
libraryBinaries,
|
|
231
|
+
ghostRenders,
|
|
232
|
+
mutateLibrary
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
//#endregion
|
|
236
|
+
//#region src/services/documents.ts
|
|
237
|
+
/**
|
|
238
|
+
* The document a placing verb acts on: the one its options name, else the
|
|
239
|
+
* active one (a document's scope fills `documentId` in through the plugin's
|
|
240
|
+
* `inScope`), and the page arguments resolved in it.
|
|
241
|
+
*/
|
|
242
|
+
function createTargets(ctx) {
|
|
243
|
+
const documents = () => ctx.get(DocumentsToken);
|
|
244
|
+
/** The document's id, or null with no document open. */
|
|
245
|
+
const documentIdOf = (documentId) => documentId ?? documents().getActiveId();
|
|
246
|
+
/** The document a verb acts on. Rejects `not-ready` with no document open. */
|
|
247
|
+
const targetOf = (options) => {
|
|
248
|
+
const documentId = documentIdOf(options?.documentId);
|
|
249
|
+
if (!documentId) throw stampError("not-ready", "no document is open");
|
|
250
|
+
return documentId;
|
|
251
|
+
};
|
|
252
|
+
/** A page argument of the document, as a ref or an index. Rejects `not-found`. */
|
|
253
|
+
const pageOf = (documentId, page) => {
|
|
254
|
+
const found = documents().getPage(page, documentId);
|
|
255
|
+
if (!found) throw stampError("not-found", `no page ${typeof page === "number" ? page : page.objectNumber} in document '${documentId}'`);
|
|
256
|
+
return found;
|
|
257
|
+
};
|
|
258
|
+
return {
|
|
259
|
+
documentIdOf,
|
|
260
|
+
targetOf,
|
|
261
|
+
pageOf
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
//#endregion
|
|
265
|
+
//#region src/services/events.ts
|
|
266
|
+
function createEvents(ctx) {
|
|
267
|
+
return {
|
|
268
|
+
libraryChanged: ctx.events.source(),
|
|
269
|
+
libraryCreated: ctx.events.source(),
|
|
270
|
+
libraryUpdated: ctx.events.source(),
|
|
271
|
+
libraryDeleted: ctx.events.source(),
|
|
272
|
+
assetCreated: ctx.events.source(),
|
|
273
|
+
assetUpdated: ctx.events.source(),
|
|
274
|
+
assetDeleted: ctx.events.source(),
|
|
275
|
+
armChanged: ctx.events.source()
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
//#endregion
|
|
279
|
+
//#region src/services/ghosts.ts
|
|
280
|
+
function createGhosts({ openAssetDocument, imageToPreview }, { ghostRenders }) {
|
|
281
|
+
const renderGhost = async (bytes, devicePixelWidth) => {
|
|
282
|
+
const doc = await openAssetDocument(new Uint8Array(bytes));
|
|
283
|
+
try {
|
|
284
|
+
const page = (await doc.pages.list()).pages[0];
|
|
285
|
+
if (!page) return null;
|
|
286
|
+
return imageToPreview(await doc.page(page.ref).render.image({
|
|
287
|
+
viewport: {
|
|
288
|
+
kind: "width",
|
|
289
|
+
width: devicePixelWidth
|
|
290
|
+
},
|
|
291
|
+
background: "transparent",
|
|
292
|
+
includeAnnotations: true,
|
|
293
|
+
format: "png"
|
|
294
|
+
}));
|
|
295
|
+
} finally {
|
|
296
|
+
await doc.close();
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
/** A resolution-aware ghost source for placement bytes: the page renders
|
|
300
|
+
* at the requested width, cached per bucket under `cacheKey` when given. */
|
|
301
|
+
const ghostProvider = (bytes, fallback, cacheKey) => {
|
|
302
|
+
const local = cacheKey ? ghostRenders.get(cacheKey) ?? /* @__PURE__ */ new Map() : /* @__PURE__ */ new Map();
|
|
303
|
+
if (cacheKey) ghostRenders.set(cacheKey, local);
|
|
304
|
+
return (devicePixelWidth) => {
|
|
305
|
+
let pending = local.get(devicePixelWidth);
|
|
306
|
+
if (!pending) {
|
|
307
|
+
pending = renderGhost(bytes, devicePixelWidth).catch((error) => {
|
|
308
|
+
globalThis.console?.warn("[stamp] ghost render failed, using the thumbnail:", error);
|
|
309
|
+
return fallback;
|
|
310
|
+
});
|
|
311
|
+
local.set(devicePixelWidth, pending);
|
|
312
|
+
}
|
|
313
|
+
return pending;
|
|
314
|
+
};
|
|
315
|
+
};
|
|
316
|
+
return { ghostProvider };
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
//#region src/services/index.ts
|
|
320
|
+
/**
|
|
321
|
+
* Plugin-private services every area is built on (not the kernel): the
|
|
322
|
+
* events, the binaries resource, the asset engine port, the ghost renderer
|
|
323
|
+
* and the document a placing verb acts on.
|
|
324
|
+
*/
|
|
325
|
+
function createServices(ctx) {
|
|
326
|
+
const binaries = createBinaries(ctx);
|
|
327
|
+
const assetEngine = createAssetEngine(ctx);
|
|
328
|
+
return {
|
|
329
|
+
events: createEvents(ctx),
|
|
330
|
+
binaries,
|
|
331
|
+
assetEngine,
|
|
332
|
+
ghosts: createGhosts(assetEngine, binaries),
|
|
333
|
+
targets: createTargets(ctx)
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
//#endregion
|
|
337
|
+
//#region src/model.ts
|
|
338
|
+
const initialStampModel = () => ({
|
|
339
|
+
libraries: {},
|
|
340
|
+
libraryOrder: [],
|
|
341
|
+
assets: {},
|
|
342
|
+
armed: {}
|
|
343
|
+
});
|
|
344
|
+
/** Remember the asset armed on a document. */
|
|
345
|
+
function armAsset(state, documentId, assetId) {
|
|
346
|
+
if (state.armed[documentId] === assetId) return state;
|
|
347
|
+
return {
|
|
348
|
+
...state,
|
|
349
|
+
armed: {
|
|
350
|
+
...state.armed,
|
|
351
|
+
[documentId]: assetId
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
/** Forget what was armed on these documents. */
|
|
356
|
+
function disarmDocuments(state, documentIds) {
|
|
357
|
+
if (!documentIds.some((documentId) => documentId in state.armed)) return state;
|
|
358
|
+
const armed = { ...state.armed };
|
|
359
|
+
for (const documentId of documentIds) delete armed[documentId];
|
|
360
|
+
return {
|
|
361
|
+
...state,
|
|
362
|
+
armed
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
/** Append a library to the display order. */
|
|
366
|
+
function addLibrary(state, library) {
|
|
367
|
+
return {
|
|
368
|
+
...state,
|
|
369
|
+
libraries: {
|
|
370
|
+
...state.libraries,
|
|
371
|
+
[library.id]: library
|
|
372
|
+
},
|
|
373
|
+
libraryOrder: [...state.libraryOrder, library.id]
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
/** Replace a known library's descriptor; an unknown id changes nothing. */
|
|
377
|
+
function setLibrary(state, library) {
|
|
378
|
+
if (!state.libraries[library.id]) return state;
|
|
379
|
+
return {
|
|
380
|
+
...state,
|
|
381
|
+
libraries: {
|
|
382
|
+
...state.libraries,
|
|
383
|
+
[library.id]: library
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
/** Remove a library together with its assets. */
|
|
388
|
+
function removeLibrary(state, libraryId) {
|
|
389
|
+
const library = state.libraries[libraryId];
|
|
390
|
+
if (!library) return state;
|
|
391
|
+
const { [libraryId]: _removed, ...libraries } = state.libraries;
|
|
392
|
+
const assets = { ...state.assets };
|
|
393
|
+
for (const id of library.assetIds) delete assets[id];
|
|
394
|
+
return {
|
|
395
|
+
...state,
|
|
396
|
+
libraries,
|
|
397
|
+
libraryOrder: state.libraryOrder.filter((id) => id !== libraryId),
|
|
398
|
+
assets
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
/** Add an asset to the end of its library; an asset of an unknown library changes nothing. */
|
|
402
|
+
function addAsset(state, asset) {
|
|
403
|
+
const library = state.libraries[asset.libraryId];
|
|
404
|
+
if (!library) return state;
|
|
405
|
+
return {
|
|
406
|
+
...state,
|
|
407
|
+
assets: {
|
|
408
|
+
...state.assets,
|
|
409
|
+
[asset.id]: asset
|
|
410
|
+
},
|
|
411
|
+
libraries: {
|
|
412
|
+
...state.libraries,
|
|
413
|
+
[library.id]: {
|
|
414
|
+
...library,
|
|
415
|
+
assetIds: [...library.assetIds, asset.id]
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
/** Replace a known asset's descriptor; an unknown id changes nothing. */
|
|
421
|
+
function setAsset(state, asset) {
|
|
422
|
+
if (!state.assets[asset.id]) return state;
|
|
423
|
+
return {
|
|
424
|
+
...state,
|
|
425
|
+
assets: {
|
|
426
|
+
...state.assets,
|
|
427
|
+
[asset.id]: asset
|
|
428
|
+
}
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
/** Remove an asset and its entry in its library's order. */
|
|
432
|
+
function removeAsset(state, assetId) {
|
|
433
|
+
const asset = state.assets[assetId];
|
|
434
|
+
if (!asset) return state;
|
|
435
|
+
const { [assetId]: _removed, ...assets } = state.assets;
|
|
436
|
+
const library = state.libraries[asset.libraryId];
|
|
437
|
+
return {
|
|
438
|
+
...state,
|
|
439
|
+
assets,
|
|
440
|
+
libraries: library ? {
|
|
441
|
+
...state.libraries,
|
|
442
|
+
[library.id]: {
|
|
443
|
+
...library,
|
|
444
|
+
assetIds: library.assetIds.filter((id) => id !== assetId)
|
|
445
|
+
}
|
|
446
|
+
} : state.libraries
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
//#endregion
|
|
450
|
+
//#region src/write/assets.ts
|
|
451
|
+
function createAssetWrites(ctx, { events, binaries, assetEngine, targets }, { resolveAssetSource }, { createLibrary }, { canCreateFromAnnotations }) {
|
|
452
|
+
const { libraryChanged, assetCreated, assetUpdated, assetDeleted } = events;
|
|
453
|
+
const { binaries: assetBinaries, libraryBinaries, ghostRenders, mutateLibrary } = binaries;
|
|
454
|
+
const { openAssetDocument, renderThumbnail } = assetEngine;
|
|
455
|
+
const { targetOf, pageOf } = targets;
|
|
456
|
+
const createAsset = async (input, options) => {
|
|
457
|
+
const signal = options?.signal;
|
|
458
|
+
throwIfCancelled(signal);
|
|
459
|
+
if (input.libraryId && !ctx.state.get().libraries[input.libraryId]) throw notFound("library", input.libraryId);
|
|
460
|
+
const resolved = await ctx.cancellable(signal, resolveAssetSource(input));
|
|
461
|
+
const meta = sniffBinaryMetadata(resolved.bytes);
|
|
462
|
+
if (!meta) throw stampError("invalid-input", "asset source must be PNG, JPEG, or single-page PDF bytes");
|
|
463
|
+
const isPdf = meta.mimeType === "application/pdf";
|
|
464
|
+
const name = input.name ?? customStampName();
|
|
465
|
+
const label = input.label ?? name;
|
|
466
|
+
if (name.length === 0 || name.includes("=")) throw stampError("invalid-input", `invalid stamp identifier '${name}': must be non-empty and contain no '='`);
|
|
467
|
+
const rasterSize = input.size ?? ("width" in meta ? {
|
|
468
|
+
width: meta.width,
|
|
469
|
+
height: meta.height
|
|
470
|
+
} : null);
|
|
471
|
+
if (!isPdf && (!rasterSize || rasterSize.width <= 0 || rasterSize.height <= 0)) throw stampError("invalid-input", "a raster asset needs a positive `size` (its page size in points)");
|
|
472
|
+
let suppliedPreview = null;
|
|
473
|
+
if (input.preview) {
|
|
474
|
+
const preview = await resolveBinarySource(input.preview);
|
|
475
|
+
suppliedPreview = {
|
|
476
|
+
bytes: new Uint8Array(preview.bytes),
|
|
477
|
+
mimeType: preview.mimeType ?? "image/png"
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
const libraryId = input.libraryId ?? (await createLibrary(label, { signal })).library.id;
|
|
481
|
+
return mutateLibrary(libraryId, async () => {
|
|
482
|
+
const liveLibrary = ctx.state.get().libraries[libraryId];
|
|
483
|
+
if (!liveLibrary) throw stampError("not-found", `library '${libraryId}' no longer exists`);
|
|
484
|
+
const assetId = assetIdFor(liveLibrary.id, name);
|
|
485
|
+
if (ctx.state.get().assets[assetId]) throw stampError("invalid-input", `library '${liveLibrary.name}' already has a stamp named '${name}'`);
|
|
486
|
+
const canonicalBytes = libraryBinaries.get(liveLibrary.id);
|
|
487
|
+
if (!canonicalBytes) throw stampError("operation-failed", `canonical bytes are missing for library '${liveLibrary.id}'`);
|
|
488
|
+
const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));
|
|
489
|
+
let appended;
|
|
490
|
+
try {
|
|
491
|
+
let page;
|
|
492
|
+
if (isPdf) {
|
|
493
|
+
const result = await doc.pages.insert(new Uint8Array(resolved.bytes));
|
|
494
|
+
if (result.insertedPages.length !== 1) throw stampError("invalid-input", "a library asset must be a single-page PDF");
|
|
495
|
+
page = result.insertedPages[0];
|
|
496
|
+
} else {
|
|
497
|
+
if (!doc.pages.flatten) throw stampError("unsupported", "raster assets need an asset engine with pages.flatten");
|
|
498
|
+
page = (await doc.pages.insertBlank({ size: rasterSize })).insertedPages[0];
|
|
499
|
+
await doc.page(page).annotations.create({
|
|
500
|
+
subtype: "stamp",
|
|
501
|
+
box: {
|
|
502
|
+
x: 0,
|
|
503
|
+
y: 0,
|
|
504
|
+
width: rasterSize.width,
|
|
505
|
+
height: rasterSize.height
|
|
506
|
+
},
|
|
507
|
+
fit: "fill"
|
|
508
|
+
}, { resources: { appearance: new Uint8Array(resolved.bytes) } });
|
|
509
|
+
if ((await doc.pages.flatten([page], { usage: "display" })).results.some(({ status }) => status !== "applied")) throw stampError("operation-failed", "flattening the raster into its page failed");
|
|
510
|
+
}
|
|
511
|
+
const layout = (await doc.pages.list()).pages.find((candidate) => candidate.ref.objectNumber === page.objectNumber);
|
|
512
|
+
const handle = doc.page(page);
|
|
513
|
+
if (!layout) throw stampError("operation-failed", "the new page is missing from the library layout");
|
|
514
|
+
await doc.pages.setName({
|
|
515
|
+
name: stampKey(name, label),
|
|
516
|
+
page
|
|
517
|
+
});
|
|
518
|
+
const asset = {
|
|
519
|
+
id: assetId,
|
|
520
|
+
libraryId: liveLibrary.id,
|
|
521
|
+
kind: input.kind ?? "stamp",
|
|
522
|
+
name,
|
|
523
|
+
label,
|
|
524
|
+
size: {
|
|
525
|
+
width: layout.size.width,
|
|
526
|
+
height: layout.size.height
|
|
527
|
+
},
|
|
528
|
+
page,
|
|
529
|
+
...input.subject !== void 0 ? { subject: input.subject } : {},
|
|
530
|
+
...input.categories !== void 0 ? { categories: input.categories } : {}
|
|
531
|
+
};
|
|
532
|
+
await handle.pieceInfo.update(STAMP_PIECEINFO_APP, stampPieceInfo(asset.kind, {
|
|
533
|
+
subject: asset.subject,
|
|
534
|
+
categories: asset.categories
|
|
535
|
+
}));
|
|
536
|
+
appended = {
|
|
537
|
+
asset,
|
|
538
|
+
bytes: await doc.pages.extract([page]),
|
|
539
|
+
preview: suppliedPreview ?? await renderThumbnail(handle),
|
|
540
|
+
canonical: await doc.download()
|
|
541
|
+
};
|
|
542
|
+
} finally {
|
|
543
|
+
await doc.close();
|
|
544
|
+
}
|
|
545
|
+
throwIfCancelled(signal);
|
|
546
|
+
libraryBinaries.set(liveLibrary.id, appended.canonical);
|
|
547
|
+
assetBinaries.set(appended.asset.id, {
|
|
548
|
+
bytes: appended.bytes,
|
|
549
|
+
preview: appended.preview
|
|
550
|
+
});
|
|
551
|
+
ctx.state.update(addAsset, appended.asset);
|
|
552
|
+
libraryChanged.emit({
|
|
553
|
+
libraryId: liveLibrary.id,
|
|
554
|
+
reason: "asset-added"
|
|
555
|
+
});
|
|
556
|
+
assetCreated.emit({
|
|
557
|
+
assetId: appended.asset.id,
|
|
558
|
+
libraryId: liveLibrary.id,
|
|
559
|
+
asset: appended.asset
|
|
560
|
+
});
|
|
561
|
+
return { asset: appended.asset };
|
|
562
|
+
}, signal);
|
|
563
|
+
};
|
|
564
|
+
const createAssetFromAnnotations = async (page, refs, input, options) => {
|
|
565
|
+
const signal = options?.signal;
|
|
566
|
+
throwIfCancelled(signal);
|
|
567
|
+
const documentId = targetOf(options);
|
|
568
|
+
if (!canCreateFromAnnotations(documentId)) throw permissionDenied("doc.download", "stamp.createAssetFromAnnotations");
|
|
569
|
+
const doc = ctx.documentHandle(documentId);
|
|
570
|
+
if (!doc) throw stampError("not-found", `document '${documentId}' is not open`);
|
|
571
|
+
const handle = doc.page(pageOf(documentId, page).ref);
|
|
572
|
+
const source = await ctx.cancellable(signal, handle.annotations.exportAppearance([...refs]));
|
|
573
|
+
return createAsset({
|
|
574
|
+
...input,
|
|
575
|
+
source
|
|
576
|
+
}, { signal });
|
|
577
|
+
};
|
|
578
|
+
const deleteAsset = async (id, options) => {
|
|
579
|
+
const signal = options?.signal;
|
|
580
|
+
throwIfCancelled(signal);
|
|
581
|
+
const initialAsset = ctx.state.get().assets[id];
|
|
582
|
+
if (!initialAsset) return;
|
|
583
|
+
return mutateLibrary(initialAsset.libraryId, async () => {
|
|
584
|
+
const asset = ctx.state.get().assets[id];
|
|
585
|
+
if (!asset) return;
|
|
586
|
+
const library = ctx.state.get().libraries[asset.libraryId];
|
|
587
|
+
if (!library) return;
|
|
588
|
+
const canonicalBytes = libraryBinaries.get(library.id);
|
|
589
|
+
if (!canonicalBytes) throw stampError("operation-failed", `canonical bytes are missing for library '${library.id}'`);
|
|
590
|
+
const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));
|
|
591
|
+
let rewritten;
|
|
592
|
+
try {
|
|
593
|
+
await doc.pages.delete([asset.page]);
|
|
594
|
+
rewritten = await doc.download();
|
|
595
|
+
} finally {
|
|
596
|
+
await doc.close();
|
|
597
|
+
}
|
|
598
|
+
throwIfCancelled(signal);
|
|
599
|
+
libraryBinaries.set(library.id, rewritten);
|
|
600
|
+
assetBinaries.delete(id);
|
|
601
|
+
ghostRenders.delete(id);
|
|
602
|
+
ctx.state.update(removeAsset, id);
|
|
603
|
+
libraryChanged.emit({
|
|
604
|
+
libraryId: library.id,
|
|
605
|
+
reason: "asset-removed"
|
|
606
|
+
});
|
|
607
|
+
assetDeleted.emit({
|
|
608
|
+
assetId: id,
|
|
609
|
+
libraryId: library.id,
|
|
610
|
+
asset: null
|
|
611
|
+
});
|
|
612
|
+
}, signal);
|
|
613
|
+
};
|
|
614
|
+
const updateAsset = async (id, patch, options) => {
|
|
615
|
+
const signal = options?.signal;
|
|
616
|
+
throwIfCancelled(signal);
|
|
617
|
+
const initial = ctx.state.get().assets[id];
|
|
618
|
+
if (!initial) throw notFound("asset", id);
|
|
619
|
+
return mutateLibrary(initial.libraryId, async () => {
|
|
620
|
+
const asset = ctx.state.get().assets[id];
|
|
621
|
+
const library = asset ? ctx.state.get().libraries[asset.libraryId] : void 0;
|
|
622
|
+
if (!asset || !library) throw notFound("asset", id);
|
|
623
|
+
const next = {
|
|
624
|
+
...asset,
|
|
625
|
+
...patch.label !== void 0 ? { label: patch.label } : {},
|
|
626
|
+
...patch.categories !== void 0 ? { categories: patch.categories } : {}
|
|
627
|
+
};
|
|
628
|
+
if (patch.subject === null) delete next.subject;
|
|
629
|
+
else if (patch.subject !== void 0) next.subject = patch.subject;
|
|
630
|
+
const canonicalBytes = libraryBinaries.get(library.id);
|
|
631
|
+
if (!canonicalBytes) throw stampError("operation-failed", `canonical bytes are missing for library '${library.id}'`);
|
|
632
|
+
const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));
|
|
633
|
+
let rewritten;
|
|
634
|
+
try {
|
|
635
|
+
if (next.label !== asset.label) await doc.pages.setName({
|
|
636
|
+
name: stampKey(asset.name, next.label),
|
|
637
|
+
page: asset.page,
|
|
638
|
+
replace: stampKey(asset.name, asset.label)
|
|
639
|
+
});
|
|
640
|
+
await doc.page(asset.page).pieceInfo.update(STAMP_PIECEINFO_APP, stampPieceInfo(next.kind, {
|
|
641
|
+
subject: next.subject,
|
|
642
|
+
categories: next.categories
|
|
643
|
+
}));
|
|
644
|
+
rewritten = await doc.download();
|
|
645
|
+
} finally {
|
|
646
|
+
await doc.close();
|
|
647
|
+
}
|
|
648
|
+
throwIfCancelled(signal);
|
|
649
|
+
libraryBinaries.set(library.id, rewritten);
|
|
650
|
+
ctx.state.update(setAsset, next);
|
|
651
|
+
libraryChanged.emit({
|
|
652
|
+
libraryId: library.id,
|
|
653
|
+
reason: "asset-updated"
|
|
654
|
+
});
|
|
655
|
+
assetUpdated.emit({
|
|
656
|
+
assetId: next.id,
|
|
657
|
+
libraryId: library.id,
|
|
658
|
+
asset: next
|
|
659
|
+
});
|
|
660
|
+
return { asset: next };
|
|
661
|
+
}, signal);
|
|
662
|
+
};
|
|
663
|
+
const moveAsset = async (id, to, options) => {
|
|
664
|
+
const signal = options?.signal;
|
|
665
|
+
throwIfCancelled(signal);
|
|
666
|
+
const asset = ctx.state.get().assets[id];
|
|
667
|
+
const binary = assetBinaries.get(id);
|
|
668
|
+
if (!asset || !binary) throw notFound("asset", id);
|
|
669
|
+
if (to.libraryId === asset.libraryId) return { asset };
|
|
670
|
+
const copy = await createAsset({
|
|
671
|
+
libraryId: to.libraryId,
|
|
672
|
+
source: new Uint8Array(binary.bytes),
|
|
673
|
+
kind: asset.kind,
|
|
674
|
+
label: asset.label,
|
|
675
|
+
...asset.subject !== void 0 ? { subject: asset.subject } : {},
|
|
676
|
+
...asset.categories ? { categories: [...asset.categories] } : {},
|
|
677
|
+
...binary.preview ? { preview: binary.preview.bytes } : {}
|
|
678
|
+
}, { signal });
|
|
679
|
+
await deleteAsset(id);
|
|
680
|
+
return copy;
|
|
681
|
+
};
|
|
682
|
+
const duplicateAsset = async (id, options) => {
|
|
683
|
+
throwIfCancelled(options?.signal);
|
|
684
|
+
const asset = ctx.state.get().assets[id];
|
|
685
|
+
const binary = assetBinaries.get(id);
|
|
686
|
+
if (!asset || !binary) throw notFound("asset", id);
|
|
687
|
+
return createAsset({
|
|
688
|
+
libraryId: asset.libraryId,
|
|
689
|
+
source: new Uint8Array(binary.bytes),
|
|
690
|
+
kind: asset.kind,
|
|
691
|
+
label: options?.label ?? `${asset.label} copy`,
|
|
692
|
+
...asset.subject !== void 0 ? { subject: asset.subject } : {},
|
|
693
|
+
...asset.categories ? { categories: [...asset.categories] } : {},
|
|
694
|
+
...binary.preview ? { preview: binary.preview.bytes } : {}
|
|
695
|
+
}, { signal: options?.signal });
|
|
696
|
+
};
|
|
697
|
+
return { api: {
|
|
698
|
+
createAsset: verb(createAsset),
|
|
699
|
+
createAssetFromAnnotations: verb(createAssetFromAnnotations),
|
|
700
|
+
updateAsset: verb(updateAsset),
|
|
701
|
+
deleteAsset: verb(deleteAsset),
|
|
702
|
+
moveAsset: verb(moveAsset),
|
|
703
|
+
duplicateAsset: verb(duplicateAsset)
|
|
704
|
+
} };
|
|
705
|
+
}
|
|
706
|
+
//#endregion
|
|
707
|
+
//#region src/blank-library.ts
|
|
708
|
+
/**
|
|
709
|
+
* The seed of a new library: a one-page PDF whose page is unregistered, the
|
|
710
|
+
* shape Acrobat itself gives a fresh stamp library (its first page is a
|
|
711
|
+
* blank starter that no `/Names /Pages` key points at). A library must be a
|
|
712
|
+
* PDF from the moment it exists, and a PDF must have a page; the unregistered
|
|
713
|
+
* blank is that page. It is never an asset, never placed, never listed.
|
|
714
|
+
*/
|
|
715
|
+
const BLANK_OBJECTS = [
|
|
716
|
+
"<< /Type /Catalog /Pages 2 0 R >>",
|
|
717
|
+
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
|
718
|
+
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"
|
|
719
|
+
];
|
|
720
|
+
let cached = null;
|
|
721
|
+
function blankLibraryPdf() {
|
|
722
|
+
if (cached) return new Uint8Array(cached);
|
|
723
|
+
let body = "%PDF-1.7\n";
|
|
724
|
+
const offsets = [];
|
|
725
|
+
BLANK_OBJECTS.forEach((object, index) => {
|
|
726
|
+
offsets.push(body.length);
|
|
727
|
+
body += `${index + 1} 0 obj\n${object}\nendobj\n`;
|
|
728
|
+
});
|
|
729
|
+
const xref = body.length;
|
|
730
|
+
body += `xref\n0 ${BLANK_OBJECTS.length + 1}\n0000000000 65535 f \n`;
|
|
731
|
+
for (const offset of offsets) body += `${String(offset).padStart(10, "0")} 00000 n \n`;
|
|
732
|
+
body += `trailer\n<< /Size ${BLANK_OBJECTS.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
|
|
733
|
+
cached = new TextEncoder().encode(body);
|
|
734
|
+
return new Uint8Array(cached);
|
|
735
|
+
}
|
|
736
|
+
//#endregion
|
|
737
|
+
//#region src/write/libraries.ts
|
|
738
|
+
/**
|
|
739
|
+
* Library writes. A library is a PDF: its `/Title` is the name, its
|
|
740
|
+
* `/Names /Pages` registry the assets, its pages the artwork, PieceInfo only
|
|
741
|
+
* what has no standard home. Every whole-PDF rewrite rides the per-library
|
|
742
|
+
* mutation queue.
|
|
743
|
+
*/
|
|
14
744
|
const entryString = (entries, key) => {
|
|
15
745
|
const entry = entries[key];
|
|
16
746
|
return entry?.type === "string" && entry.value.length > 0 ? entry.value : void 0;
|
|
@@ -23,7 +753,6 @@ const entryStringArray = (entries, key) => {
|
|
|
23
753
|
const entry = entries[key];
|
|
24
754
|
return entry?.type === "string-array" ? [...entry.value] : void 0;
|
|
25
755
|
};
|
|
26
|
-
const kindToPdfName = (kind) => kind === "signature" ? "Signature" : kind === "initials" ? "Initials" : "Stamp";
|
|
27
756
|
const kindFromPdfName = (name) => {
|
|
28
757
|
switch (name?.toLowerCase()) {
|
|
29
758
|
case "stamp": return "stamp";
|
|
@@ -32,167 +761,159 @@ const kindFromPdfName = (name) => {
|
|
|
32
761
|
default: return;
|
|
33
762
|
}
|
|
34
763
|
};
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
* are derived page extractions; this map owns the rewritten whole PDF. */
|
|
56
|
-
const libraryBinaries = /* @__PURE__ */ new Map();
|
|
57
|
-
/** Whole-PDF rewrites must be serialized per library or two concurrent
|
|
58
|
-
* appends could both start from the same bytes and lose one page. */
|
|
59
|
-
const libraryMutationTails = /* @__PURE__ */ new Map();
|
|
60
|
-
const mutateLibrary = (libraryId, mutation) => {
|
|
61
|
-
const result = (libraryMutationTails.get(libraryId) ?? Promise.resolve()).then(mutation);
|
|
62
|
-
const tail = result.then(() => void 0, () => void 0);
|
|
63
|
-
libraryMutationTails.set(libraryId, tail);
|
|
64
|
-
return result.finally(() => {
|
|
65
|
-
if (libraryMutationTails.get(libraryId) === tail) libraryMutationTails.delete(libraryId);
|
|
66
|
-
});
|
|
67
|
-
};
|
|
68
|
-
let assetEngineRef = null;
|
|
69
|
-
const assetEngine = () => {
|
|
70
|
-
if (!assetEngineRef) {
|
|
71
|
-
const cfg = config.assetEngine;
|
|
72
|
-
assetEngineRef = !cfg ? ctx.engine : typeof cfg === "function" ? cfg() : cfg;
|
|
73
|
-
}
|
|
74
|
-
return assetEngineRef;
|
|
75
|
-
};
|
|
76
|
-
const openAssetDocument = async (bytes, identity) => {
|
|
764
|
+
const allocateId = (preferred, prefix, taken) => {
|
|
765
|
+
let id = preferred;
|
|
766
|
+
if (!id || taken.has(id)) do
|
|
767
|
+
id = uid(prefix);
|
|
768
|
+
while (taken.has(id));
|
|
769
|
+
taken.add(id);
|
|
770
|
+
return id;
|
|
771
|
+
};
|
|
772
|
+
function createLibraryWrites(ctx, { events, binaries, assetEngine }) {
|
|
773
|
+
const { libraryChanged, libraryCreated, libraryUpdated, libraryDeleted, assetCreated } = events;
|
|
774
|
+
const { binaries: assetBinaries, libraryBinaries, ghostRenders, mutateLibrary } = binaries;
|
|
775
|
+
const { openAssetDocument, renderThumbnail } = assetEngine;
|
|
776
|
+
const createLibrary = async (name, options) => {
|
|
777
|
+
const signal = options?.signal;
|
|
778
|
+
throwIfCancelled(signal);
|
|
779
|
+
const kind = options?.kind ?? "stamps";
|
|
780
|
+
const taken = new Set(Object.keys(ctx.state.get().libraries));
|
|
781
|
+
const id = allocateId(options?.id, "stamp-lib", taken);
|
|
782
|
+
const doc = await ctx.cancellable(signal, openAssetDocument(blankLibraryPdf()));
|
|
783
|
+
let bytes;
|
|
77
784
|
try {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
} catch (err) {
|
|
87
|
-
if (!config.assetEngine && EngineError.is(err, EngineErrorCode.InvalidArg)) throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] importing a library PDF needs an engine that can open local bytes, and this viewer's engine cannot (cloud). Pass stampPlugin({ assetEngine: () => import('@embedpdf/engine').then((m) => m.createLocalEngine()) }) — it loads lazily, on first import.");
|
|
88
|
-
throw err;
|
|
785
|
+
await doc.metadata.update({ title: name });
|
|
786
|
+
await doc.pieceInfo.update(STAMP_LIBRARY_PIECEINFO_APP, stampLibraryPieceInfo(id, {
|
|
787
|
+
kind,
|
|
788
|
+
categories: options?.categories
|
|
789
|
+
}));
|
|
790
|
+
bytes = await doc.download();
|
|
791
|
+
} finally {
|
|
792
|
+
await doc.close();
|
|
89
793
|
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
mimeType: image.contentType
|
|
794
|
+
throwIfCancelled(signal);
|
|
795
|
+
const library = {
|
|
796
|
+
id,
|
|
797
|
+
name,
|
|
798
|
+
kind,
|
|
799
|
+
assetIds: [],
|
|
800
|
+
...options?.categories ? { categories: options.categories } : {}
|
|
98
801
|
};
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
const createLooseLibrary = (name) => {
|
|
109
|
-
const id = uid("stamp-lib");
|
|
110
|
-
ctx.dispatch({
|
|
111
|
-
type: "LIBRARY_ADDED",
|
|
112
|
-
library: {
|
|
113
|
-
id,
|
|
114
|
-
name,
|
|
115
|
-
storage: "loose",
|
|
116
|
-
assetIds: []
|
|
117
|
-
}
|
|
802
|
+
libraryBinaries.set(id, bytes);
|
|
803
|
+
ctx.state.update(addLibrary, library);
|
|
804
|
+
libraryChanged.emit({
|
|
805
|
+
libraryId: id,
|
|
806
|
+
reason: "created"
|
|
807
|
+
});
|
|
808
|
+
libraryCreated.emit({
|
|
809
|
+
libraryId: id,
|
|
810
|
+
library
|
|
118
811
|
});
|
|
119
|
-
return
|
|
812
|
+
return { library };
|
|
120
813
|
};
|
|
121
|
-
const
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
const
|
|
814
|
+
const importLibrary = async (source, options) => {
|
|
815
|
+
const signal = options?.signal;
|
|
816
|
+
throwIfCancelled(signal);
|
|
817
|
+
const resolved = await ctx.cancellable(signal, resolveBinarySource(source));
|
|
818
|
+
if (sniffBinaryMetadata(resolved.bytes)?.mimeType !== "application/pdf") throw stampError("invalid-input", "importLibrary needs PDF bytes (use createAsset for a raster image)");
|
|
819
|
+
const doc = await ctx.cancellable(signal, openAssetDocument(new Uint8Array(resolved.bytes)));
|
|
125
820
|
let imported;
|
|
126
821
|
try {
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
if (!handle.pieceInfo) throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] canonical PDF libraries need page pieceInfo support");
|
|
133
|
-
return {
|
|
134
|
-
layout,
|
|
135
|
-
handle,
|
|
136
|
-
metadata: null
|
|
137
|
-
};
|
|
138
|
-
});
|
|
139
|
-
const catalogMetadata = await doc.pieceInfo.read(LIBRARY_PIECEINFO_APP);
|
|
140
|
-
for (const page of pages) page.metadata = await page.handle.pieceInfo.read(STAMP_PIECEINFO_APP);
|
|
141
|
-
const state = ctx.getState();
|
|
142
|
-
const takenLibraryIds = new Set(Object.keys(state.libraries));
|
|
143
|
-
const takenAssetIds = new Set(Object.keys(state.assets));
|
|
144
|
-
const catalogEntries = catalogMetadata?.entries ?? {};
|
|
822
|
+
const layout = await doc.pages.list();
|
|
823
|
+
if (layout.pageCount === 0) throw stampError("invalid-input", "a canonical stamp library PDF must contain at least one page");
|
|
824
|
+
const pagesByObjectNumber = new Map(layout.pages.map((page) => [page.ref.objectNumber, page]));
|
|
825
|
+
const catalogEntries = (await doc.pieceInfo.get("EMBD_StampLibrary"))?.entries ?? {};
|
|
826
|
+
const takenLibraryIds = new Set(Object.keys(ctx.state.get().libraries));
|
|
145
827
|
const libraryId = allocateId(entryString(catalogEntries, "Id"), "stamp-lib", takenLibraryIds);
|
|
146
|
-
const
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
828
|
+
const docMeta = await doc.metadata.get();
|
|
829
|
+
const libraryName = (docMeta.title && docMeta.title.length > 0 ? docMeta.title : void 0) ?? entryString(catalogEntries, "Name") ?? options?.name ?? "Stamps";
|
|
830
|
+
if (!docMeta.title) await doc.metadata.update({ title: libraryName });
|
|
831
|
+
const libraryCategories = options?.categories ?? entryStringArray(catalogEntries, "Categories");
|
|
832
|
+
const libraryLocale = entryString(catalogEntries, "Locale");
|
|
833
|
+
const libraryKind = options?.libraryKind ?? libraryKindFromPdfName(entryName(catalogEntries, "Kind"));
|
|
834
|
+
const registry = (layout.namedPages ?? []).filter((entry) => entry.target.kind === "page");
|
|
835
|
+
const hidden = (layout.namedPages ?? []).filter((entry) => entry.target.kind !== "page");
|
|
836
|
+
if (hidden.length > 0) globalThis.console?.warn(`[stamp] library '${libraryName}' carries ${hidden.length} hidden-template or dangling registration(s); they are not stamps and were ignored`);
|
|
837
|
+
let descriptors;
|
|
838
|
+
if (registry.length > 0) {
|
|
839
|
+
const seen = /* @__PURE__ */ new Set();
|
|
840
|
+
descriptors = registry.map((entry) => {
|
|
841
|
+
const { name, label } = parseStampKey(entry.name);
|
|
842
|
+
if (!name) throw stampError("invalid-input", `library '${libraryName}': empty stamp identifier in key '${entry.name}'`);
|
|
843
|
+
if (seen.has(name)) throw stampError("invalid-input", `library '${libraryName}': duplicate stamp identifier '${name}'`);
|
|
844
|
+
seen.add(name);
|
|
845
|
+
const page = pagesByObjectNumber.get(entry.target.page.objectNumber);
|
|
846
|
+
return {
|
|
847
|
+
page: page.ref,
|
|
848
|
+
index: page.index,
|
|
849
|
+
name,
|
|
850
|
+
label
|
|
851
|
+
};
|
|
852
|
+
});
|
|
853
|
+
descriptors.sort((left, right) => left.index - right.index);
|
|
854
|
+
} else if (layout.namedPages === void 0) throw stampError("unsupported", "the asset engine reports no named-page registry; an engine with named pages is needed to import libraries");
|
|
855
|
+
else {
|
|
856
|
+
descriptors = [];
|
|
857
|
+
for (const page of layout.pages) {
|
|
858
|
+
const version1Entries = (await doc.page(page.ref).pieceInfo.get(STAMP_PIECEINFO_APP))?.entries;
|
|
859
|
+
const name = (version1Entries && entryString(version1Entries, "Name")) ?? `Stamp${page.index + 1}`;
|
|
860
|
+
const label = (version1Entries && entryString(version1Entries, "Subject")) ?? options?.assetName?.(page.index) ?? name;
|
|
861
|
+
descriptors.push({
|
|
862
|
+
page: page.ref,
|
|
863
|
+
index: page.index,
|
|
864
|
+
name,
|
|
865
|
+
label
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
for (const descriptor of descriptors) await doc.pages.setName({
|
|
869
|
+
name: stampKey(descriptor.name, descriptor.label),
|
|
870
|
+
page: descriptor.page
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
await doc.pieceInfo.update(STAMP_LIBRARY_PIECEINFO_APP, stampLibraryPieceInfo(libraryId, {
|
|
874
|
+
kind: libraryKind,
|
|
875
|
+
categories: libraryCategories,
|
|
876
|
+
locale: libraryLocale
|
|
877
|
+
}));
|
|
171
878
|
const assets = [];
|
|
172
879
|
for (const descriptor of descriptors) {
|
|
173
|
-
const
|
|
174
|
-
await handle.pieceInfo.
|
|
175
|
-
const
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
880
|
+
const handle = doc.page(descriptor.page);
|
|
881
|
+
const entries = (await handle.pieceInfo.get("EMBD_Stamp"))?.entries ?? {};
|
|
882
|
+
const kind = options?.kind ?? kindFromPdfName(entryName(entries, "Kind")) ?? "stamp";
|
|
883
|
+
const subject = entryString(entries, "SubjectOverride");
|
|
884
|
+
const categories = entryStringArray(entries, "Categories");
|
|
885
|
+
const page = pagesByObjectNumber.get(descriptor.page.objectNumber);
|
|
886
|
+
const asset = {
|
|
887
|
+
id: assetIdFor(libraryId, descriptor.name),
|
|
888
|
+
libraryId,
|
|
889
|
+
kind,
|
|
890
|
+
name: descriptor.name,
|
|
891
|
+
label: descriptor.label,
|
|
892
|
+
size: {
|
|
893
|
+
width: page.size.width,
|
|
894
|
+
height: page.size.height
|
|
180
895
|
},
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
}
|
|
896
|
+
page: descriptor.page,
|
|
897
|
+
...subject !== void 0 ? { subject } : {},
|
|
898
|
+
...categories !== void 0 ? { categories } : {}
|
|
899
|
+
};
|
|
900
|
+
await handle.pieceInfo.update(STAMP_PIECEINFO_APP, stampPieceInfo(kind, {
|
|
901
|
+
subject,
|
|
902
|
+
categories
|
|
903
|
+
}));
|
|
904
|
+
const bytes = await doc.pages.extract([descriptor.page]);
|
|
185
905
|
assets.push({
|
|
186
906
|
asset,
|
|
187
907
|
bytes,
|
|
188
|
-
preview:
|
|
908
|
+
preview: await renderThumbnail(handle)
|
|
189
909
|
});
|
|
190
910
|
}
|
|
191
911
|
imported = {
|
|
192
912
|
library: {
|
|
193
913
|
id: libraryId,
|
|
194
914
|
name: libraryName,
|
|
195
|
-
|
|
915
|
+
kind: libraryKind,
|
|
916
|
+
...libraryLocale ? { locale: libraryLocale } : {},
|
|
196
917
|
categories: libraryCategories,
|
|
197
918
|
assetIds: []
|
|
198
919
|
},
|
|
@@ -202,231 +923,305 @@ function createStampCapability(ctx, config = {}) {
|
|
|
202
923
|
} finally {
|
|
203
924
|
await doc.close();
|
|
204
925
|
}
|
|
926
|
+
throwIfCancelled(signal);
|
|
205
927
|
libraryBinaries.set(imported.library.id, imported.canonicalBytes);
|
|
206
|
-
ctx.
|
|
207
|
-
type: "LIBRARY_ADDED",
|
|
208
|
-
library: imported.library
|
|
209
|
-
});
|
|
928
|
+
ctx.state.update(addLibrary, imported.library);
|
|
210
929
|
for (const { asset, bytes, preview } of imported.assets) {
|
|
211
|
-
|
|
930
|
+
assetBinaries.set(asset.id, {
|
|
212
931
|
bytes,
|
|
213
932
|
preview
|
|
214
933
|
});
|
|
215
|
-
ctx.
|
|
216
|
-
type: "ASSET_ADDED",
|
|
217
|
-
asset
|
|
218
|
-
});
|
|
934
|
+
ctx.state.update(addAsset, asset);
|
|
219
935
|
}
|
|
220
|
-
|
|
936
|
+
libraryChanged.emit({
|
|
937
|
+
libraryId: imported.library.id,
|
|
938
|
+
reason: "imported"
|
|
939
|
+
});
|
|
940
|
+
libraryCreated.emit({
|
|
941
|
+
libraryId: imported.library.id,
|
|
942
|
+
library: imported.library
|
|
943
|
+
});
|
|
944
|
+
for (const { asset } of imported.assets) assetCreated.emit({
|
|
945
|
+
assetId: asset.id,
|
|
946
|
+
libraryId: imported.library.id,
|
|
947
|
+
asset
|
|
948
|
+
});
|
|
949
|
+
return { library: ctx.state.get().libraries[imported.library.id] ?? imported.library };
|
|
221
950
|
};
|
|
222
|
-
const
|
|
223
|
-
const
|
|
224
|
-
if (
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
if (!meta) throw new EngineError(EngineErrorCode.InvalidArg, "[stamp] asset source must be PNG, JPEG, or single-page PDF bytes");
|
|
228
|
-
const isPdf = meta.mimeType === "application/pdf";
|
|
229
|
-
let suppliedPreview = null;
|
|
230
|
-
if (input.preview) {
|
|
231
|
-
const preview = await resolveBinarySource(input.preview);
|
|
232
|
-
suppliedPreview = {
|
|
233
|
-
bytes: new Uint8Array(preview.bytes),
|
|
234
|
-
mimeType: preview.mimeType ?? "image/png"
|
|
235
|
-
};
|
|
951
|
+
const dropLibrary = (id) => {
|
|
952
|
+
const library = ctx.state.get().libraries[id];
|
|
953
|
+
if (library) for (const assetId of library.assetIds) {
|
|
954
|
+
assetBinaries.delete(assetId);
|
|
955
|
+
ghostRenders.delete(assetId);
|
|
236
956
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const pageObjectNumber = result.insertedPageObjectNumbers[0];
|
|
252
|
-
const layout = result.layout.pages.find((candidate) => candidate.pageObjectNumber === pageObjectNumber);
|
|
253
|
-
const page = doc.page(pageObjectNumber);
|
|
254
|
-
if (!layout || !page.pieceInfo) throw new EngineError(EngineErrorCode.NotImplemented, "[stamp] canonical PDF libraries need page layout and pieceInfo support");
|
|
255
|
-
const asset = {
|
|
256
|
-
id: assetId,
|
|
257
|
-
libraryId: liveLibrary.id,
|
|
258
|
-
kind: input.kind ?? "stamp",
|
|
259
|
-
name: input.name,
|
|
260
|
-
size: {
|
|
261
|
-
width: layout.size.width,
|
|
262
|
-
height: layout.size.height
|
|
263
|
-
},
|
|
264
|
-
format: "pdf",
|
|
265
|
-
pageObjectNumber,
|
|
266
|
-
subject: input.subject,
|
|
267
|
-
categories: input.categories
|
|
268
|
-
};
|
|
269
|
-
await page.pieceInfo.update(STAMP_PIECEINFO_APP, metadataPatch(asset.id, asset.name, asset.kind, asset.subject, asset.categories));
|
|
270
|
-
const bytes = await doc.pages.extract([pageObjectNumber]);
|
|
271
|
-
let preview = suppliedPreview;
|
|
272
|
-
if (!preview) preview = imageToPreview(await page.render.image({
|
|
273
|
-
viewport: {
|
|
274
|
-
kind: "width",
|
|
275
|
-
width: config.previewWidth ?? DEFAULT_PREVIEW_WIDTH
|
|
276
|
-
},
|
|
277
|
-
background: "transparent",
|
|
278
|
-
includeAnnotations: true,
|
|
279
|
-
format: "png"
|
|
280
|
-
}));
|
|
281
|
-
appended = {
|
|
282
|
-
asset,
|
|
283
|
-
bytes,
|
|
284
|
-
preview,
|
|
285
|
-
canonical: await doc.download()
|
|
286
|
-
};
|
|
287
|
-
} finally {
|
|
288
|
-
await doc.close();
|
|
289
|
-
}
|
|
290
|
-
libraryBinaries.set(liveLibrary.id, appended.canonical);
|
|
291
|
-
binaries.set(appended.asset.id, {
|
|
292
|
-
bytes: appended.bytes,
|
|
293
|
-
preview: appended.preview
|
|
294
|
-
});
|
|
295
|
-
ctx.dispatch({
|
|
296
|
-
type: "ASSET_ADDED",
|
|
297
|
-
asset: appended.asset
|
|
298
|
-
});
|
|
299
|
-
return appended.asset.id;
|
|
957
|
+
libraryBinaries.delete(id);
|
|
958
|
+
ctx.state.update(removeLibrary, id);
|
|
959
|
+
};
|
|
960
|
+
const deleteLibrary = (id, options) => mutateLibrary(id, async () => {
|
|
961
|
+
const existed = ctx.state.get().libraries[id] !== void 0;
|
|
962
|
+
dropLibrary(id);
|
|
963
|
+
if (existed) {
|
|
964
|
+
libraryChanged.emit({
|
|
965
|
+
libraryId: id,
|
|
966
|
+
reason: "removed"
|
|
967
|
+
});
|
|
968
|
+
libraryDeleted.emit({
|
|
969
|
+
libraryId: id,
|
|
970
|
+
library: null
|
|
300
971
|
});
|
|
301
972
|
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
if (!
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
kind: input.kind ?? "stamp",
|
|
317
|
-
name: input.name,
|
|
318
|
-
size,
|
|
319
|
-
format: isPdf ? "pdf" : meta.mimeType === "image/png" ? "png" : "jpeg",
|
|
320
|
-
subject: input.subject,
|
|
321
|
-
categories: input.categories
|
|
973
|
+
}, options?.signal);
|
|
974
|
+
const updateLibrary = async (id, patch, options) => {
|
|
975
|
+
const signal = options?.signal;
|
|
976
|
+
throwIfCancelled(signal);
|
|
977
|
+
if (!ctx.state.get().libraries[id]) throw notFound("library", id);
|
|
978
|
+
return mutateLibrary(id, async () => {
|
|
979
|
+
const library = ctx.state.get().libraries[id];
|
|
980
|
+
if (!library) throw notFound("library", id);
|
|
981
|
+
const canonicalBytes = libraryBinaries.get(id);
|
|
982
|
+
if (!canonicalBytes) throw stampError("operation-failed", `canonical bytes are missing for library '${id}'`);
|
|
983
|
+
const next = {
|
|
984
|
+
...library,
|
|
985
|
+
...patch.name !== void 0 ? { name: patch.name } : {},
|
|
986
|
+
...patch.categories !== void 0 ? { categories: patch.categories } : {}
|
|
322
987
|
};
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
988
|
+
const doc = await ctx.cancellable(signal, openAssetDocument(canonicalBytes));
|
|
989
|
+
let rewritten;
|
|
990
|
+
try {
|
|
991
|
+
if (next.name !== library.name) await doc.metadata.update({ title: next.name });
|
|
992
|
+
await doc.pieceInfo.update(STAMP_LIBRARY_PIECEINFO_APP, stampLibraryPieceInfo(id, {
|
|
993
|
+
kind: next.kind,
|
|
994
|
+
categories: next.categories,
|
|
995
|
+
locale: next.locale
|
|
996
|
+
}));
|
|
997
|
+
rewritten = await doc.download();
|
|
998
|
+
} finally {
|
|
999
|
+
await doc.close();
|
|
1000
|
+
}
|
|
1001
|
+
throwIfCancelled(signal);
|
|
1002
|
+
libraryBinaries.set(id, rewritten);
|
|
1003
|
+
ctx.state.update(setLibrary, next);
|
|
1004
|
+
libraryChanged.emit({
|
|
1005
|
+
libraryId: id,
|
|
1006
|
+
reason: "updated"
|
|
326
1007
|
});
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
1008
|
+
libraryUpdated.emit({
|
|
1009
|
+
libraryId: id,
|
|
1010
|
+
library: next
|
|
330
1011
|
});
|
|
331
|
-
return
|
|
332
|
-
};
|
|
333
|
-
if (!targetLibrary) return commitLooseAsset(createLooseLibrary(input.name));
|
|
334
|
-
return mutateLibrary(targetLibrary.id, async () => {
|
|
335
|
-
const liveLibrary = ctx.getState().libraries[targetLibrary.id];
|
|
336
|
-
if (liveLibrary?.storage !== "loose") throw new EngineError(EngineErrorCode.NotFound, `[stamp] loose library '${targetLibrary.id}' no longer exists`);
|
|
337
|
-
return commitLooseAsset(liveLibrary.id);
|
|
338
|
-
});
|
|
1012
|
+
return { library: next };
|
|
1013
|
+
}, signal);
|
|
339
1014
|
};
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
}
|
|
1015
|
+
return {
|
|
1016
|
+
createLibrary,
|
|
1017
|
+
api: {
|
|
1018
|
+
createLibrary: verb(createLibrary),
|
|
1019
|
+
updateLibrary: verb(updateLibrary),
|
|
1020
|
+
importLibrary: verb(importLibrary),
|
|
1021
|
+
deleteLibrary: verb(deleteLibrary)
|
|
1022
|
+
}
|
|
348
1023
|
};
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
1024
|
+
}
|
|
1025
|
+
//#endregion
|
|
1026
|
+
//#region src/write/marks.ts
|
|
1027
|
+
/**
|
|
1028
|
+
* Authoring: a drawn or typed mark rendered to a one-page PDF (the
|
|
1029
|
+
* annotation is authored on a scratch page and exported the way "stamp from
|
|
1030
|
+
* selection" exports), a page of a PDF as a single-page PDF, and the bytes
|
|
1031
|
+
* an asset is made from.
|
|
1032
|
+
*/
|
|
1033
|
+
/** A mark's `#rrggbb` color, checked before anything is drawn. */
|
|
1034
|
+
const hexColor = (hex) => {
|
|
1035
|
+
const color = hex.trim();
|
|
1036
|
+
if (!/^#[0-9a-f]{6}$/i.test(color)) throw stampError("invalid-input", `mark color must be #rrggbb, got '${hex}'`);
|
|
1037
|
+
return color;
|
|
1038
|
+
};
|
|
1039
|
+
/** An exact ArrayBuffer over a view (the engine's binary idiom). */
|
|
1040
|
+
const toArrayBuffer = (bytes) => {
|
|
1041
|
+
const buffer = new ArrayBuffer(bytes.byteLength);
|
|
1042
|
+
new Uint8Array(buffer).set(bytes);
|
|
1043
|
+
return buffer;
|
|
1044
|
+
};
|
|
1045
|
+
/** An ink mark's strokes, as the engine takes them; a mark needs at least one point. */
|
|
1046
|
+
const inkListOf = (strokes) => {
|
|
1047
|
+
if (!strokes.some((stroke) => stroke.length > 0)) throw stampError("invalid-input", "an ink mark needs at least one point");
|
|
1048
|
+
return strokes.map((stroke) => stroke.map(({ x, y }) => ({
|
|
1049
|
+
x,
|
|
1050
|
+
y
|
|
1051
|
+
})));
|
|
1052
|
+
};
|
|
1053
|
+
/**
|
|
1054
|
+
* A generous box for typed text. The export keeps the whole box, so the
|
|
1055
|
+
* text is centered in it: the mark then sits in the middle of a preview
|
|
1056
|
+
* or a signature field.
|
|
1057
|
+
*/
|
|
1058
|
+
const textBounds = (text, fontSize) => ({
|
|
1059
|
+
x: 0,
|
|
1060
|
+
y: 0,
|
|
1061
|
+
width: Math.max(1, text.length) * fontSize * .75 + fontSize,
|
|
1062
|
+
height: fontSize * 1.6
|
|
1063
|
+
});
|
|
1064
|
+
function createMarks({ assetEngine }) {
|
|
1065
|
+
const { openAssetDocument, registerFont } = assetEngine;
|
|
1066
|
+
/**
|
|
1067
|
+
* A drawn or typed mark rendered to a one-page PDF: the annotation is
|
|
1068
|
+
* authored on a scratch page and exported the way "stamp from selection"
|
|
1069
|
+
* exports — a fresh page the size of the mark, paths kept as paths, the
|
|
1070
|
+
* font subset-embedded. Self-contained and Acrobat-readable.
|
|
1071
|
+
*/
|
|
1072
|
+
const renderMark = async (mark) => {
|
|
1073
|
+
if (mark.kind === "text") await registerFont(mark.fontFamily);
|
|
1074
|
+
const doc = await openAssetDocument(blankLibraryPdf());
|
|
1075
|
+
try {
|
|
1076
|
+
const scratch = (await doc.pages.list()).pages[0];
|
|
1077
|
+
if (!scratch) throw stampError("operation-failed", "the scratch document has no page");
|
|
1078
|
+
const page = doc.page(scratch.ref);
|
|
1079
|
+
const color = hexColor(mark.color ?? "#1d2b53");
|
|
1080
|
+
const created = mark.kind === "ink" ? await page.annotations.create({
|
|
1081
|
+
subtype: "ink",
|
|
1082
|
+
inkList: inkListOf(mark.strokes),
|
|
1083
|
+
color,
|
|
1084
|
+
strokeWidth: mark.strokeWidth ?? 2
|
|
1085
|
+
}) : await page.annotations.create({
|
|
1086
|
+
subtype: "free-text",
|
|
1087
|
+
intent: "free-text",
|
|
1088
|
+
contents: mark.text,
|
|
1089
|
+
fontFamily: mark.fontFamily,
|
|
1090
|
+
fontSize: mark.fontSize ?? 36,
|
|
1091
|
+
textAlign: "center",
|
|
1092
|
+
verticalAlign: "middle",
|
|
1093
|
+
box: textBounds(mark.text, mark.fontSize ?? 36),
|
|
1094
|
+
fontColor: color,
|
|
1095
|
+
strokeWidth: 0
|
|
378
1096
|
});
|
|
379
|
-
|
|
1097
|
+
return new Uint8Array(await page.annotations.exportAppearance([created.annotation.ref]));
|
|
1098
|
+
} finally {
|
|
1099
|
+
await doc.close();
|
|
1100
|
+
}
|
|
380
1101
|
};
|
|
381
|
-
|
|
382
|
-
const
|
|
1102
|
+
/** One page of a PDF as a single-page PDF (a `pdf` mark with `pageIndex`). */
|
|
1103
|
+
const extractPage = async (bytes, pageIndex) => {
|
|
1104
|
+
const doc = await openAssetDocument(bytes);
|
|
383
1105
|
try {
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
if (
|
|
387
|
-
|
|
388
|
-
|
|
1106
|
+
const layout = await doc.pages.list();
|
|
1107
|
+
const page = layout.pages[pageIndex];
|
|
1108
|
+
if (!page) throw stampError("invalid-input", `the PDF has no page ${pageIndex} (${layout.pageCount} pages)`);
|
|
1109
|
+
return await doc.pages.extract([page.ref]);
|
|
1110
|
+
} finally {
|
|
1111
|
+
await doc.close();
|
|
1112
|
+
}
|
|
1113
|
+
};
|
|
1114
|
+
/** The bytes an asset is made from: the caller's `source`, or its `mark` authored into one. */
|
|
1115
|
+
const resolveAssetSource = async (input) => {
|
|
1116
|
+
if (input.source === void 0 === (input.mark === void 0)) throw stampError("invalid-input", "createAsset takes exactly one of `source` / `mark`");
|
|
1117
|
+
if (input.source !== void 0) return resolveBinarySource(input.source);
|
|
1118
|
+
const mark = input.mark;
|
|
1119
|
+
switch (mark.kind) {
|
|
1120
|
+
case "image": return resolveBinarySource(mark.source);
|
|
1121
|
+
case "pdf": {
|
|
1122
|
+
const resolved = await resolveBinarySource(mark.source);
|
|
1123
|
+
if (mark.pageIndex === void 0) return resolved;
|
|
1124
|
+
return { bytes: toArrayBuffer(await extractPage(new Uint8Array(resolved.bytes), mark.pageIndex)) };
|
|
1125
|
+
}
|
|
1126
|
+
case "ink":
|
|
1127
|
+
case "text": return { bytes: toArrayBuffer(await renderMark(mark)) };
|
|
389
1128
|
}
|
|
390
1129
|
};
|
|
1130
|
+
return { resolveAssetSource };
|
|
1131
|
+
}
|
|
1132
|
+
//#endregion
|
|
1133
|
+
//#region src/write/placement.ts
|
|
1134
|
+
/**
|
|
1135
|
+
* Placement: arm an asset on a document (the next click places) or place it
|
|
1136
|
+
* without the pointer. Form-backed stamps are executable templates only
|
|
1137
|
+
* until placement — they are evaluated on an isolated copy under the target
|
|
1138
|
+
* document's detached script realm, so neither the canonical library nor
|
|
1139
|
+
* its reusable per-page extraction becomes target/user/time specific.
|
|
1140
|
+
*/
|
|
1141
|
+
function createPlacement(ctx, { binaries, assetEngine, ghosts, targets }, { canPlace }) {
|
|
1142
|
+
const { binaries: assetBinaries, libraryBinaries } = binaries;
|
|
1143
|
+
const { openAssetDocument, imageToPreview } = assetEngine;
|
|
1144
|
+
const { ghostProvider } = ghosts;
|
|
1145
|
+
const { documentIdOf, targetOf, pageOf } = targets;
|
|
1146
|
+
const settings = ctx.settings();
|
|
1147
|
+
const droppedArms = () => Object.keys(ctx.state.get().armed).filter((documentId) => !ctx.tryForDocument(AnnotationToken$1, documentId)?.stamps.isArmed()).join("\n");
|
|
1148
|
+
ctx.watch(droppedArms, (dropped) => {
|
|
1149
|
+
if (dropped) ctx.state.update(disarmDocuments, dropped.split("\n"));
|
|
1150
|
+
});
|
|
1151
|
+
/** The one payload both entry points hand the annotation plugin: artwork,
|
|
1152
|
+
* a resolution-aware ghost, true size, and the identity a placement
|
|
1153
|
+
* writes (`/Name` = identifier, `/Subj` = the subject override or label). */
|
|
1154
|
+
const stampPayload = (asset, placement, materialized) => ({
|
|
1155
|
+
source: placement.bytes,
|
|
1156
|
+
preview: ghostProvider(placement.bytes, placement.preview, materialized ? null : asset.id),
|
|
1157
|
+
intrinsicSize: asset.size,
|
|
1158
|
+
name: asset.name,
|
|
1159
|
+
subject: asset.subject ?? asset.label
|
|
1160
|
+
});
|
|
391
1161
|
/**
|
|
392
1162
|
* Form-backed stamps are executable templates only until placement. Work
|
|
393
1163
|
* on an isolated copy so neither the canonical library nor its reusable
|
|
394
1164
|
* per-page extraction becomes target/user/time specific.
|
|
1165
|
+
*
|
|
1166
|
+
* The realm comes from the target document's actions plugin: a detached
|
|
1167
|
+
* realm under that document's policy and environment, with its own
|
|
1168
|
+
* sandbox and none of the viewer realm's globals. No actions plugin,
|
|
1169
|
+
* scripting off, or `dynamic: false`: the template is armed as-is.
|
|
395
1170
|
*/
|
|
396
|
-
const materializeForPlacement = async (documentId, asset,
|
|
397
|
-
if (
|
|
398
|
-
const
|
|
399
|
-
const
|
|
400
|
-
if (!
|
|
1171
|
+
const materializeForPlacement = async (documentId, asset, binary) => {
|
|
1172
|
+
if (!settings.get().dynamic) return binary;
|
|
1173
|
+
const actions = ctx.tryForDocument(ActionsToken$1, documentId);
|
|
1174
|
+
const mintRealm = actions?.createDetachedScriptRealm;
|
|
1175
|
+
if (!actions || !mintRealm) return binary;
|
|
1176
|
+
const documents = ctx.get(DocumentsToken);
|
|
1177
|
+
const target = documents.get(documentId);
|
|
1178
|
+
if (target?.status !== "ready") throw stampError("not-found", `document '${documentId}' is not open`);
|
|
1179
|
+
const targetDocument = {
|
|
1180
|
+
name: target.name,
|
|
1181
|
+
pageCount: target.pageCount,
|
|
1182
|
+
pages: documents.listPages(documentId)
|
|
1183
|
+
};
|
|
401
1184
|
const canonicalBytes = libraryBinaries.get(asset.libraryId);
|
|
402
|
-
const sourceBytes = canonicalBytes ??
|
|
403
|
-
const doc = await openAssetDocument(new Uint8Array(sourceBytes)
|
|
1185
|
+
const sourceBytes = canonicalBytes ?? binary.bytes;
|
|
1186
|
+
const doc = await openAssetDocument(new Uint8Array(sourceBytes));
|
|
1187
|
+
let realm = null;
|
|
404
1188
|
let scripting = null;
|
|
405
1189
|
try {
|
|
406
1190
|
const layout = await doc.pages.list();
|
|
407
|
-
const selectedPage = asset.
|
|
408
|
-
if (!selectedPage) throw
|
|
1191
|
+
const selectedPage = asset.page === void 0 ? layout.pageCount === 1 ? layout.pages[0] : void 0 : layout.pages.find(({ ref }) => ref.objectNumber === asset.page.objectNumber);
|
|
1192
|
+
if (!selectedPage) throw stampError("invalid-input", canonicalBytes ? `canonical page ${asset.page?.objectNumber ?? "unknown"} no longer exists` : "a loose dynamic stamp asset must contain exactly one page");
|
|
409
1193
|
const snapshot = await doc.forms.list();
|
|
410
|
-
if (!snapshot.fields.some((field) => field.widgets.some(({
|
|
411
|
-
if (!doc.pages.flatten || !doc.pages.extract) throw
|
|
412
|
-
|
|
413
|
-
scripting = createFormScriptingController({
|
|
1194
|
+
if (!snapshot.fields.some((field) => field.widgets.some(({ page }) => page?.objectNumber === selectedPage.ref.objectNumber))) return binary;
|
|
1195
|
+
if (!doc.pages.flatten || !doc.pages.extract) throw stampError("unsupported", "dynamic PDF stamps need an asset engine with pages.flatten and pages.extract");
|
|
1196
|
+
realm = mintRealm.call(actions, {
|
|
414
1197
|
doc,
|
|
415
|
-
document: () =>
|
|
416
|
-
|
|
417
|
-
|
|
1198
|
+
document: () => targetDocument,
|
|
1199
|
+
bootSources: async () => {
|
|
1200
|
+
return (doc.actions ? await doc.actions.get() : null)?.nameTreeScripts.map(({ action }) => javaScriptProgramFromActionTree(action)) ?? [];
|
|
1201
|
+
}
|
|
1202
|
+
});
|
|
1203
|
+
scripting = createFormScriptingController({
|
|
1204
|
+
document: () => targetDocument,
|
|
1205
|
+
transaction: realm.transaction.bind(realm),
|
|
1206
|
+
budget: realm.budget
|
|
1207
|
+
});
|
|
1208
|
+
const result = await scripting.transaction(async (scripts) => {
|
|
1209
|
+
const calculated = await scripts.recalculate(snapshot);
|
|
1210
|
+
if (calculated.status === "accepted" && calculated.effects.length > 0) await doc.apply({ ops: formEffectOps(calculated.effects) });
|
|
1211
|
+
return calculated;
|
|
1212
|
+
});
|
|
1213
|
+
actions.surfaceScriptCommit(result, {
|
|
1214
|
+
origin: "user",
|
|
1215
|
+
realm: "detached"
|
|
418
1216
|
});
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
const
|
|
423
|
-
const
|
|
424
|
-
if (failed) throw new EngineError(EngineErrorCode.Unknown, `[stamp] dynamic stamp flatten failed for page ${failed.pageObjectNumber}`);
|
|
425
|
-
const bytes = await doc.pages.extract([pageObjectNumber]);
|
|
426
|
-
const image = await doc.page(pageObjectNumber).render.image({
|
|
1217
|
+
if (result.status === "failed") throw stampError("operation-failed", `dynamic stamp scripting failed: ${result.error?.message ?? "native form effect failed"}`);
|
|
1218
|
+
const page = selectedPage.ref;
|
|
1219
|
+
await doc.pages.flatten([page], { usage: "display" });
|
|
1220
|
+
const bytes = await doc.pages.extract([page]);
|
|
1221
|
+
const image = await doc.page(page).render.image({
|
|
427
1222
|
viewport: {
|
|
428
1223
|
kind: "width",
|
|
429
|
-
width:
|
|
1224
|
+
width: settings.get().previewWidth
|
|
430
1225
|
},
|
|
431
1226
|
background: "transparent",
|
|
432
1227
|
includeAnnotations: false,
|
|
@@ -438,152 +1233,280 @@ function createStampCapability(ctx, config = {}) {
|
|
|
438
1233
|
};
|
|
439
1234
|
} finally {
|
|
440
1235
|
scripting?.dispose();
|
|
1236
|
+
realm?.dispose();
|
|
441
1237
|
await doc.close();
|
|
442
1238
|
}
|
|
443
1239
|
};
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
const
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
mimeType: placement.preview.mimeType
|
|
454
|
-
} : void 0,
|
|
455
|
-
intrinsicSize: asset.size,
|
|
456
|
-
targetWidth: opts?.targetWidth
|
|
457
|
-
});
|
|
1240
|
+
/** An asset and its bytes, or `not-found`. */
|
|
1241
|
+
const assetOf = (assetId) => {
|
|
1242
|
+
const asset = ctx.state.get().assets[assetId];
|
|
1243
|
+
const binary = assetBinaries.get(assetId);
|
|
1244
|
+
if (!asset || !binary) throw notFound("asset", assetId);
|
|
1245
|
+
return {
|
|
1246
|
+
asset,
|
|
1247
|
+
binary
|
|
1248
|
+
};
|
|
458
1249
|
};
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
1250
|
+
/** Placing is annotation work: refused where the document's annotation plugin refuses a create. */
|
|
1251
|
+
const assertMayPlace = (documentId, operation) => {
|
|
1252
|
+
if (!canPlace(documentId)) throw permissionDenied("annotations:create", operation);
|
|
1253
|
+
};
|
|
1254
|
+
const armAsset$1 = async (assetId, options) => {
|
|
1255
|
+
const signal = options?.signal;
|
|
1256
|
+
throwIfCancelled(signal);
|
|
1257
|
+
const documentId = targetOf(options);
|
|
1258
|
+
const { asset, binary } = assetOf(assetId);
|
|
1259
|
+
assertMayPlace(documentId, "stamp.armAsset");
|
|
1260
|
+
const placement = await ctx.cancellable(signal, materializeForPlacement(documentId, asset, binary));
|
|
1261
|
+
throwIfCancelled(signal);
|
|
1262
|
+
await ctx.forDocument(AnnotationToken, documentId).stamps.arm({
|
|
1263
|
+
...stampPayload(asset, placement, placement !== binary),
|
|
1264
|
+
targetWidth: options?.targetWidth
|
|
1265
|
+
}, { signal });
|
|
1266
|
+
ctx.state.update(armAsset, documentId, assetId);
|
|
1267
|
+
};
|
|
1268
|
+
const getArmedAsset = (documentId) => {
|
|
1269
|
+
const id = documentIdOf(documentId);
|
|
1270
|
+
const assetId = id === null ? void 0 : ctx.state.get().armed[id];
|
|
1271
|
+
if (id === null || assetId === void 0) return null;
|
|
1272
|
+
if (!ctx.tryForDocument(AnnotationToken$1, id)?.stamps.isArmed()) return null;
|
|
1273
|
+
return ctx.state.get().assets[assetId] ?? null;
|
|
1274
|
+
};
|
|
1275
|
+
const disarm = (documentId) => {
|
|
1276
|
+
const id = documentIdOf(documentId);
|
|
1277
|
+
if (id === null) return;
|
|
1278
|
+
ctx.tryForDocument(AnnotationToken, id)?.stamps.disarm();
|
|
1279
|
+
ctx.state.update(disarmDocuments, [id]);
|
|
1280
|
+
};
|
|
1281
|
+
/** Place on one document, its permission already checked. */
|
|
1282
|
+
const placeOn = async (documentId, assetId, placement, signal) => {
|
|
1283
|
+
const { asset, binary } = assetOf(assetId);
|
|
1284
|
+
const materialized = await ctx.cancellable(signal, materializeForPlacement(documentId, asset, binary));
|
|
1285
|
+
throwIfCancelled(signal);
|
|
1286
|
+
return ctx.forDocument(AnnotationToken, documentId).stamps.place(stampPayload(asset, materialized, materialized !== binary), placement, { signal });
|
|
491
1287
|
};
|
|
1288
|
+
const placeAsset = async (assetId, placement, options) => {
|
|
1289
|
+
throwIfCancelled(options?.signal);
|
|
1290
|
+
const documentId = targetOf(options);
|
|
1291
|
+
assetOf(assetId);
|
|
1292
|
+
assertMayPlace(documentId, "stamp.placeAsset");
|
|
1293
|
+
return placeOn(documentId, assetId, placement, options?.signal);
|
|
1294
|
+
};
|
|
1295
|
+
const placeAssetOnPages = async (assetId, pages, placement, options) => {
|
|
1296
|
+
const signal = options?.signal;
|
|
1297
|
+
throwIfCancelled(signal);
|
|
1298
|
+
const documentId = targetOf(options);
|
|
1299
|
+
assetOf(assetId);
|
|
1300
|
+
assertMayPlace(documentId, "stamp.placeAssetOnPages");
|
|
1301
|
+
const targetPages = pages === "all" ? ctx.get(DocumentsToken).listPages(documentId).map((page) => page.ref) : pages.map((page) => pageOf(documentId, page).ref);
|
|
1302
|
+
const applied = [];
|
|
1303
|
+
const failed = [];
|
|
1304
|
+
for (const page of targetPages) try {
|
|
1305
|
+
const placed = await placeOn(documentId, assetId, {
|
|
1306
|
+
...placement,
|
|
1307
|
+
page
|
|
1308
|
+
}, signal);
|
|
1309
|
+
applied.push(placed.annotation);
|
|
1310
|
+
} catch (error) {
|
|
1311
|
+
const refused = toPluginError("stamp", error);
|
|
1312
|
+
if (refused.code === "operation-cancelled") throw refused;
|
|
1313
|
+
failed.push({
|
|
1314
|
+
ref: page,
|
|
1315
|
+
error: toPluginErrorInfo(refused)
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
return {
|
|
1319
|
+
applied,
|
|
1320
|
+
skipped: [],
|
|
1321
|
+
failed
|
|
1322
|
+
};
|
|
1323
|
+
};
|
|
1324
|
+
return { api: {
|
|
1325
|
+
armAsset: verb(armAsset$1),
|
|
1326
|
+
disarm,
|
|
1327
|
+
getArmedAsset,
|
|
1328
|
+
placeAsset: verb(placeAsset),
|
|
1329
|
+
placeAssetOnPages: verb(placeAssetOnPages)
|
|
1330
|
+
} };
|
|
492
1331
|
}
|
|
493
1332
|
//#endregion
|
|
494
|
-
//#region src/
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
delete libraries[action.libraryId];
|
|
517
|
-
const assets = { ...state.assets };
|
|
518
|
-
for (const id of library.assetIds) delete assets[id];
|
|
519
|
-
return {
|
|
520
|
-
...state,
|
|
521
|
-
libraries,
|
|
522
|
-
libraryOrder: state.libraryOrder.filter((id) => id !== action.libraryId),
|
|
523
|
-
assets
|
|
524
|
-
};
|
|
525
|
-
}
|
|
526
|
-
case "ASSET_ADDED": {
|
|
527
|
-
const library = state.libraries[action.asset.libraryId];
|
|
528
|
-
if (!library) return state;
|
|
529
|
-
return {
|
|
530
|
-
...state,
|
|
531
|
-
assets: {
|
|
532
|
-
...state.assets,
|
|
533
|
-
[action.asset.id]: action.asset
|
|
534
|
-
},
|
|
535
|
-
libraries: {
|
|
536
|
-
...state.libraries,
|
|
537
|
-
[library.id]: {
|
|
538
|
-
...library,
|
|
539
|
-
assetIds: [...library.assetIds, action.asset.id]
|
|
540
|
-
}
|
|
541
|
-
}
|
|
542
|
-
};
|
|
1333
|
+
//#region src/controller.ts
|
|
1334
|
+
/**
|
|
1335
|
+
* The stamp controller: the composition root. It builds the plugin's
|
|
1336
|
+
* services once, wires each area with the services it declares, and
|
|
1337
|
+
* assembles the capability from the areas' API slices. Every verb and read
|
|
1338
|
+
* has a home in `read/` or `write/`; the one state-change event is derived
|
|
1339
|
+
* here.
|
|
1340
|
+
*/
|
|
1341
|
+
function createStampController(ctx) {
|
|
1342
|
+
const services = createServices(ctx);
|
|
1343
|
+
const { events } = services;
|
|
1344
|
+
const settings = ctx.settings();
|
|
1345
|
+
ctx.state.onChange(({ previous, next }) => {
|
|
1346
|
+
if (previous.armed === next.armed) return;
|
|
1347
|
+
const documentIds = /* @__PURE__ */ new Set([...Object.keys(previous.armed), ...Object.keys(next.armed)]);
|
|
1348
|
+
for (const documentId of documentIds) {
|
|
1349
|
+
const assetId = next.armed[documentId];
|
|
1350
|
+
if (previous.armed[documentId] === assetId) continue;
|
|
1351
|
+
events.armChanged.emit({
|
|
1352
|
+
documentId,
|
|
1353
|
+
asset: assetId === void 0 ? null : next.assets[assetId] ?? null
|
|
1354
|
+
});
|
|
543
1355
|
}
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
1356
|
+
});
|
|
1357
|
+
const catalog = createCatalog(ctx, services);
|
|
1358
|
+
const marks = createMarks(services);
|
|
1359
|
+
const libraries = createLibraryWrites(ctx, services);
|
|
1360
|
+
const assets = createAssetWrites(ctx, services, marks, libraries, catalog);
|
|
1361
|
+
const placement = createPlacement(ctx, services, catalog);
|
|
1362
|
+
return { api: composeApi("stamp", [
|
|
1363
|
+
settings.api,
|
|
1364
|
+
catalog.api,
|
|
1365
|
+
libraries.api,
|
|
1366
|
+
assets.api,
|
|
1367
|
+
placement.api,
|
|
1368
|
+
{
|
|
1369
|
+
onLibraryChanged: events.libraryChanged.on,
|
|
1370
|
+
onLibraryCreated: events.libraryCreated.on,
|
|
1371
|
+
onLibraryUpdated: events.libraryUpdated.on,
|
|
1372
|
+
onLibraryDeleted: events.libraryDeleted.on,
|
|
1373
|
+
onAssetCreated: events.assetCreated.on,
|
|
1374
|
+
onAssetUpdated: events.assetUpdated.on,
|
|
1375
|
+
onAssetDeleted: events.assetDeleted.on,
|
|
1376
|
+
onArmChanged: events.armChanged.on
|
|
561
1377
|
}
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
};
|
|
565
|
-
//#endregion
|
|
566
|
-
//#region src/types.ts
|
|
567
|
-
const StampToken = createCapabilityToken("stamp");
|
|
1378
|
+
]) };
|
|
1379
|
+
}
|
|
568
1380
|
//#endregion
|
|
569
1381
|
//#region src/stamp.plugin.ts
|
|
570
1382
|
/**
|
|
571
|
-
*
|
|
572
|
-
* document; placement
|
|
573
|
-
*
|
|
574
|
-
* because the annotation token is document-scoped and resolved lazily per
|
|
575
|
-
* placement (a viewer without the annotation plugin fails at the arm call,
|
|
576
|
-
* with the kernel's own missing-capability error).
|
|
1383
|
+
* Stamp libraries and assets. Workspace-scoped: libraries outlive any one
|
|
1384
|
+
* document; placement targets a document through its annotation plugin.
|
|
1385
|
+
* `config` is the settings the app registers, over {@link STAMP_DEFAULTS}.
|
|
577
1386
|
*/
|
|
578
|
-
const stampPlugin = (config
|
|
1387
|
+
const stampPlugin = (config) => definePlugin({
|
|
579
1388
|
id: "stamp",
|
|
580
1389
|
token: StampToken,
|
|
581
1390
|
scope: "workspace",
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
1391
|
+
optional: [AnnotationToken, ActionsToken],
|
|
1392
|
+
state: initialStampModel,
|
|
1393
|
+
settings: {
|
|
1394
|
+
defaults: STAMP_DEFAULTS,
|
|
1395
|
+
registered: config,
|
|
1396
|
+
whole: ["assetEngine", "fonts"]
|
|
1397
|
+
},
|
|
1398
|
+
create: createStampController,
|
|
1399
|
+
inScope: (stamp, documentId) => {
|
|
1400
|
+
const scoped = (options) => ({
|
|
1401
|
+
...options,
|
|
1402
|
+
documentId: options?.documentId ?? documentId
|
|
1403
|
+
});
|
|
1404
|
+
return {
|
|
1405
|
+
...stamp,
|
|
1406
|
+
createAssetFromAnnotations: (page, refs, input, options) => stamp.createAssetFromAnnotations(page, refs, input, scoped(options)),
|
|
1407
|
+
armAsset: (assetId, options) => stamp.armAsset(assetId, scoped(options)),
|
|
1408
|
+
disarm: (target = documentId) => stamp.disarm(target),
|
|
1409
|
+
getArmedAsset: (target = documentId) => stamp.getArmedAsset(target),
|
|
1410
|
+
placeAsset: (assetId, placement, options) => stamp.placeAsset(assetId, placement, scoped(options)),
|
|
1411
|
+
placeAssetOnPages: (assetId, pages, placement, options) => stamp.placeAssetOnPages(assetId, pages, placement, scoped(options)),
|
|
1412
|
+
canPlace: (target = documentId) => stamp.canPlace(target),
|
|
1413
|
+
canCreateFromAnnotations: (target = documentId) => stamp.canCreateFromAnnotations(target)
|
|
1414
|
+
};
|
|
1415
|
+
}
|
|
585
1416
|
});
|
|
586
1417
|
//#endregion
|
|
587
|
-
|
|
1418
|
+
//#region src/state.ts
|
|
1419
|
+
/**
|
|
1420
|
+
* The stamps page's State table as code: what `useStampState()` returns, and
|
|
1421
|
+
* the same fields in every other framework. It reads the document in scope,
|
|
1422
|
+
* else the active one. The libraries and their stamps are not here:
|
|
1423
|
+
* `useStampLibraries()` and `useStampAssets()` read them, so a component that
|
|
1424
|
+
* only shows the armed stamp doesn't re-render when a library changes.
|
|
1425
|
+
*/
|
|
1426
|
+
const stampState = defineState(StampToken, {
|
|
1427
|
+
read: (stamp) => ({ armedAsset: stamp.getArmedAsset() }),
|
|
1428
|
+
empty: { armedAsset: null }
|
|
1429
|
+
});
|
|
1430
|
+
//#endregion
|
|
1431
|
+
//#region src/persistence.ts
|
|
1432
|
+
/** An in-memory store, for tests and SSR. */
|
|
1433
|
+
function memoryStampStore() {
|
|
1434
|
+
const rows = /* @__PURE__ */ new Map();
|
|
1435
|
+
return {
|
|
1436
|
+
list: async () => [...rows.entries()].map(([id, bytes]) => ({
|
|
1437
|
+
id,
|
|
1438
|
+
bytes
|
|
1439
|
+
})),
|
|
1440
|
+
put: async (id, bytes) => {
|
|
1441
|
+
rows.set(id, new Uint8Array(bytes));
|
|
1442
|
+
},
|
|
1443
|
+
delete: async (id) => {
|
|
1444
|
+
rows.delete(id);
|
|
1445
|
+
}
|
|
1446
|
+
};
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* Bring every stored library back: each PDF is imported as-is (its title,
|
|
1450
|
+
* registry, and PieceInfo id come from the file; the store's key is only a
|
|
1451
|
+
* hint). Call once at boot, before seeding defaults, so "already has
|
|
1452
|
+
* libraries" means the user's own.
|
|
1453
|
+
*/
|
|
1454
|
+
async function restoreStampLibraries(stamp, store) {
|
|
1455
|
+
const restored = [];
|
|
1456
|
+
for (const { id, bytes } of await store.list()) try {
|
|
1457
|
+
restored.push((await stamp.importLibrary(bytes)).library.id);
|
|
1458
|
+
} catch (error) {
|
|
1459
|
+
globalThis.console?.warn(`[stamp] stored library '${id}' could not be restored:`, error);
|
|
1460
|
+
}
|
|
1461
|
+
return restored;
|
|
1462
|
+
}
|
|
1463
|
+
/**
|
|
1464
|
+
* Keep the store in sync from now on: every canonical change saves the
|
|
1465
|
+
* library's PDF, a removal deletes it. `except` names libraries never to
|
|
1466
|
+
* persist (the bundled default set, typically). Returns the unsubscribe;
|
|
1467
|
+
* work already asked for still finishes.
|
|
1468
|
+
*
|
|
1469
|
+
* Each library has one line of store work, so saves never overlap and a
|
|
1470
|
+
* delete never lands under a late save. The changes of one burst (one call
|
|
1471
|
+
* into the plugin) are one save; the changes made while a save runs are one
|
|
1472
|
+
* more after it.
|
|
1473
|
+
*/
|
|
1474
|
+
function persistStampLibraries(stamp, store, options = {}) {
|
|
1475
|
+
const except = new Set(options.except ?? []);
|
|
1476
|
+
/** Per library: the store step waiting or running, and the one to follow it. */
|
|
1477
|
+
const lines = /* @__PURE__ */ new Map();
|
|
1478
|
+
const run = (libraryId, step) => {
|
|
1479
|
+
const line = lines.get(libraryId);
|
|
1480
|
+
if (line) {
|
|
1481
|
+
if (line.started) line.next = step;
|
|
1482
|
+
else line.step = step;
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
const fresh = {
|
|
1486
|
+
step,
|
|
1487
|
+
started: false,
|
|
1488
|
+
next: null
|
|
1489
|
+
};
|
|
1490
|
+
lines.set(libraryId, fresh);
|
|
1491
|
+
Promise.resolve().then(async () => {
|
|
1492
|
+
fresh.started = true;
|
|
1493
|
+
try {
|
|
1494
|
+
if (fresh.step === "save") await store.put(libraryId, await stamp.exportLibrary(libraryId));
|
|
1495
|
+
else await store.delete(libraryId);
|
|
1496
|
+
} catch (error) {
|
|
1497
|
+
const doing = fresh.step === "save" ? "persisting" : "deleting stored";
|
|
1498
|
+
globalThis.console?.warn(`[stamp] ${doing} library '${libraryId}' failed:`, error);
|
|
1499
|
+
}
|
|
1500
|
+
lines.delete(libraryId);
|
|
1501
|
+
if (fresh.next) run(libraryId, fresh.next);
|
|
1502
|
+
});
|
|
1503
|
+
};
|
|
1504
|
+
return stamp.onLibraryChanged(({ libraryId, reason }) => {
|
|
1505
|
+
if (except.has(libraryId)) return;
|
|
1506
|
+
run(libraryId, reason === "removed" ? "delete" : "save");
|
|
1507
|
+
});
|
|
1508
|
+
}
|
|
1509
|
+
//#endregion
|
|
1510
|
+
export { DEFAULT_LIBRARY_KIND, STAMP_DEFAULTS, StampToken, memoryStampStore, persistStampLibraries, restoreStampLibraries, stampPlugin, stampState };
|
|
588
1511
|
|
|
589
1512
|
//# sourceMappingURL=index.js.map
|