@embedpdf/plugin-stamp 3.0.0-next.2 → 3.0.0-next.21

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