pdf-mapview 0.1.0

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.
@@ -0,0 +1,738 @@
1
+ import { z } from 'zod';
2
+ import { randomUUID } from 'crypto';
3
+ import { resolve, join, extname, basename, dirname } from 'path';
4
+ import { writeFile, readFile, rm, mkdir } from 'fs/promises';
5
+ import { createCanvas, DOMMatrix, ImageData, Path2D } from '@napi-rs/canvas';
6
+ import sharp2 from 'sharp';
7
+
8
+ // src/shared/manifest.ts
9
+ var normalizedPointSchema = z.object({
10
+ x: z.number().finite().min(0).max(1),
11
+ y: z.number().finite().min(0).max(1)
12
+ });
13
+ var normalizedRectSchema = z.object({
14
+ x: z.number().finite().min(0).max(1),
15
+ y: z.number().finite().min(0).max(1),
16
+ width: z.number().finite().min(0).max(1),
17
+ height: z.number().finite().min(0).max(1)
18
+ });
19
+ var regionFeatureSchema = z.object({
20
+ id: z.string().min(1),
21
+ geometry: z.discriminatedUnion("type", [
22
+ z.object({
23
+ type: z.literal("polygon"),
24
+ points: z.array(normalizedPointSchema).min(3)
25
+ }),
26
+ z.object({
27
+ type: z.literal("rectangle"),
28
+ rect: normalizedRectSchema
29
+ }),
30
+ z.object({
31
+ type: z.literal("point"),
32
+ point: normalizedPointSchema,
33
+ radius: z.number().finite().positive().optional()
34
+ }),
35
+ z.object({
36
+ type: z.literal("label"),
37
+ point: normalizedPointSchema,
38
+ text: z.string().min(1)
39
+ })
40
+ ]),
41
+ label: z.string().optional(),
42
+ metadata: z.record(z.unknown()).optional()
43
+ });
44
+ var regionCollectionSchema = z.object({
45
+ type: z.literal("FeatureCollection"),
46
+ regions: z.array(regionFeatureSchema)
47
+ });
48
+
49
+ // src/shared/manifest.ts
50
+ var tileLevelSchema = z.object({
51
+ z: z.number().int().min(0),
52
+ width: z.number().int().positive(),
53
+ height: z.number().int().positive(),
54
+ columns: z.number().int().positive(),
55
+ rows: z.number().int().positive(),
56
+ scale: z.number().positive()
57
+ });
58
+ var manifestSchema = z.object({
59
+ version: z.literal(1),
60
+ kind: z.literal("pdf-map"),
61
+ id: z.string().min(1),
62
+ source: z.object({
63
+ type: z.union([z.literal("pdf"), z.literal("image")]),
64
+ originalFilename: z.string().optional(),
65
+ page: z.number().int().positive().optional(),
66
+ width: z.number().int().positive(),
67
+ height: z.number().int().positive(),
68
+ mimeType: z.string().optional()
69
+ }),
70
+ coordinateSpace: z.object({
71
+ normalized: z.literal(true),
72
+ width: z.number().int().positive(),
73
+ height: z.number().int().positive()
74
+ }),
75
+ tiles: z.object({
76
+ tileSize: z.number().int().positive(),
77
+ format: z.union([z.literal("webp"), z.literal("jpeg"), z.literal("png")]),
78
+ minZoom: z.number().int().min(0),
79
+ maxZoom: z.number().int().min(0),
80
+ pathTemplate: z.string().min(1),
81
+ levels: z.array(tileLevelSchema)
82
+ }),
83
+ view: z.object({
84
+ defaultCenter: z.tuple([
85
+ z.number().finite().min(0).max(1),
86
+ z.number().finite().min(0).max(1)
87
+ ]),
88
+ defaultZoom: z.number().finite(),
89
+ minZoom: z.number().finite(),
90
+ maxZoom: z.number().finite()
91
+ }),
92
+ overlays: z.object({
93
+ inline: regionCollectionSchema.optional(),
94
+ url: z.string().optional()
95
+ }).optional(),
96
+ assets: z.object({
97
+ preview: z.string().optional()
98
+ }).optional(),
99
+ metadata: z.object({
100
+ title: z.string().optional(),
101
+ createdAt: z.string().optional()
102
+ }).catchall(z.unknown()).optional()
103
+ });
104
+ function createManifest(input) {
105
+ return manifestSchema.parse({
106
+ version: 1,
107
+ kind: "pdf-map",
108
+ ...input
109
+ });
110
+ }
111
+ function parseManifest(input) {
112
+ return manifestSchema.parse(input);
113
+ }
114
+ function resolveTileUrl(args) {
115
+ const template = args.overrideTemplate ?? args.manifest.tiles.pathTemplate;
116
+ const relative = template.replaceAll("{z}", String(args.z)).replaceAll("{x}", String(args.x)).replaceAll("{y}", String(args.y));
117
+ if (/^https?:\/\//.test(relative)) {
118
+ return relative;
119
+ }
120
+ if (!args.baseUrl) {
121
+ return relative;
122
+ }
123
+ if (/^https?:\/\//.test(args.baseUrl)) {
124
+ return new URL(relative.replace(/^\//, ""), ensureTrailingSlash(args.baseUrl)).toString();
125
+ }
126
+ return joinRelativeUrl(args.baseUrl, relative);
127
+ }
128
+ function ensureTrailingSlash(value) {
129
+ return value.endsWith("/") ? value : `${value}/`;
130
+ }
131
+ function joinRelativeUrl(baseUrl, path) {
132
+ const normalizedBase = ensureLeadingSlash(stripTrailingSlash(baseUrl));
133
+ const normalizedPath = stripLeadingSlash(path);
134
+ if (!normalizedPath) {
135
+ return normalizedBase || "/";
136
+ }
137
+ return normalizedBase ? `${normalizedBase}/${normalizedPath}` : `/${normalizedPath}`;
138
+ }
139
+ function stripLeadingSlash(value) {
140
+ return value.replace(/^\/+/, "");
141
+ }
142
+ function stripTrailingSlash(value) {
143
+ return value.replace(/\/+$/, "");
144
+ }
145
+ function ensureLeadingSlash(value) {
146
+ if (!value) {
147
+ return "";
148
+ }
149
+ return value.startsWith("/") ? value : `/${value}`;
150
+ }
151
+
152
+ // src/shared/bytes.ts
153
+ function toUint8Array(input) {
154
+ if (input instanceof ArrayBuffer) {
155
+ return new Uint8Array(input);
156
+ }
157
+ return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
158
+ }
159
+
160
+ // src/ingest/pipeline/inspectInput.ts
161
+ async function inspectInput(input) {
162
+ if (typeof input === "string") {
163
+ const bytes = await readFile(input);
164
+ return {
165
+ bytes: toUint8Array(bytes),
166
+ originalFilename: basename(input),
167
+ ext: extname(input).slice(1).toLowerCase() || void 0
168
+ };
169
+ }
170
+ return {
171
+ bytes: toUint8Array(input)
172
+ };
173
+ }
174
+ async function rasterizePdf(options) {
175
+ installNodeCanvasGlobals();
176
+ const pdfjs = await import('pdfjs-dist/legacy/build/pdf.mjs');
177
+ const loadingTask = pdfjs.getDocument({
178
+ data: options.bytes,
179
+ useSystemFonts: true
180
+ });
181
+ const pdf = await loadingTask.promise;
182
+ const page = await pdf.getPage(options.page);
183
+ const viewport = page.getViewport({ scale: 1 });
184
+ const scale = resolveScale({
185
+ viewportWidth: viewport.width,
186
+ viewportHeight: viewport.height,
187
+ maxDimension: options.maxDimension,
188
+ rasterDpi: options.rasterDpi
189
+ });
190
+ const scaledViewport = page.getViewport({
191
+ scale: scale <= 0 ? 1 : scale
192
+ });
193
+ const canvas = createCanvas(Math.ceil(scaledViewport.width), Math.ceil(scaledViewport.height));
194
+ const context = canvas.getContext("2d");
195
+ context.fillStyle = options.background;
196
+ context.fillRect(0, 0, canvas.width, canvas.height);
197
+ await page.render({
198
+ canvasContext: context,
199
+ viewport: scaledViewport
200
+ }).promise;
201
+ const png = await canvas.encode("png");
202
+ await page.cleanup();
203
+ await pdf.cleanup();
204
+ await pdf.destroy();
205
+ return {
206
+ bytes: new Uint8Array(png),
207
+ width: canvas.width,
208
+ height: canvas.height,
209
+ mimeType: "image/png"
210
+ };
211
+ }
212
+ function installNodeCanvasGlobals() {
213
+ if (!("DOMMatrix" in globalThis)) {
214
+ globalThis.DOMMatrix = DOMMatrix;
215
+ }
216
+ if (!("ImageData" in globalThis)) {
217
+ globalThis.ImageData = ImageData;
218
+ }
219
+ if (!("Path2D" in globalThis)) {
220
+ globalThis.Path2D = Path2D;
221
+ }
222
+ }
223
+ function resolveScale(options) {
224
+ if (options.rasterDpi && Number.isFinite(options.rasterDpi) && options.rasterDpi > 0) {
225
+ return options.rasterDpi / 72;
226
+ }
227
+ return Math.min(
228
+ 1,
229
+ options.maxDimension / Math.max(options.viewportWidth, options.viewportHeight)
230
+ );
231
+ }
232
+
233
+ // src/ingest/storage/memory.ts
234
+ function memoryStorageAdapter() {
235
+ const artifacts = [];
236
+ const record = (kind, path, contentType, bytes) => {
237
+ const artifact = {
238
+ kind,
239
+ path,
240
+ contentType,
241
+ size: bytes.byteLength
242
+ };
243
+ artifacts.push(artifact);
244
+ return artifact;
245
+ };
246
+ return {
247
+ async writeTile(args) {
248
+ return record("tile", `tiles/${args.z}/${args.x}/${args.y}.${args.ext}`, args.contentType, args.bytes);
249
+ },
250
+ async writeManifest(args) {
251
+ return record("manifest", args.path, args.contentType, args.bytes);
252
+ },
253
+ async writeAsset(args) {
254
+ return record(args.kind, args.path, args.contentType, args.bytes);
255
+ },
256
+ async finalize(_args) {
257
+ return {
258
+ artifacts: [...artifacts]
259
+ };
260
+ }
261
+ };
262
+ }
263
+ async function normalizeImage(options) {
264
+ const { data, info } = await sharp2(options.bytes, { failOn: "none" }).rotate().resize({
265
+ width: options.maxDimension,
266
+ height: options.maxDimension,
267
+ fit: "inside",
268
+ withoutEnlargement: true
269
+ }).flatten({
270
+ background: options.background
271
+ }).png().toBuffer({ resolveWithObject: true });
272
+ return {
273
+ bytes: new Uint8Array(data),
274
+ width: info.width,
275
+ height: info.height,
276
+ mimeType: "image/png"
277
+ };
278
+ }
279
+ async function buildTilePyramid(options) {
280
+ const maxZoom = Math.max(
281
+ 0,
282
+ Math.ceil(Math.log2(Math.max(options.width, options.height) / options.tileSize))
283
+ );
284
+ const levels = [];
285
+ const tiles = [];
286
+ const source = Buffer.from(options.image);
287
+ for (let z3 = 0; z3 <= maxZoom; z3 += 1) {
288
+ const scale = 1 / 2 ** (maxZoom - z3);
289
+ const width = Math.max(1, Math.ceil(options.width * scale));
290
+ const height = Math.max(1, Math.ceil(options.height * scale));
291
+ const columns = Math.max(1, Math.ceil(width / options.tileSize));
292
+ const rows = Math.max(1, Math.ceil(height / options.tileSize));
293
+ levels.push({
294
+ z: z3,
295
+ width,
296
+ height,
297
+ columns,
298
+ rows,
299
+ scale
300
+ });
301
+ const levelBuffer = await sharp2(source, { failOn: "none" }).resize({
302
+ width,
303
+ height,
304
+ fit: "fill"
305
+ }).png().toBuffer();
306
+ for (let y = 0; y < rows; y += 1) {
307
+ for (let x = 0; x < columns; x += 1) {
308
+ const left = x * options.tileSize;
309
+ const top = y * options.tileSize;
310
+ const extractWidth = Math.min(options.tileSize, width - left);
311
+ const extractHeight = Math.min(options.tileSize, height - top);
312
+ const tileBuffer = await sharp2(levelBuffer, { failOn: "none" }).extract({
313
+ left,
314
+ top,
315
+ width: extractWidth,
316
+ height: extractHeight
317
+ }).toFormat(options.format, formatOptions(options.format, options.quality)).toBuffer();
318
+ tiles.push({
319
+ kind: "tile",
320
+ path: `tiles/${z3}/${x}/${y}.${extensionForFormat(options.format)}`,
321
+ contentType: contentTypeForFormat(options.format),
322
+ bytes: new Uint8Array(tileBuffer)
323
+ });
324
+ }
325
+ }
326
+ }
327
+ const previewBuffer = await sharp2(source, { failOn: "none" }).resize({
328
+ width: 1024,
329
+ height: 1024,
330
+ fit: "inside",
331
+ withoutEnlargement: true
332
+ }).webp({ quality: 80 }).toBuffer();
333
+ return {
334
+ levels,
335
+ tiles,
336
+ preview: {
337
+ kind: "preview",
338
+ path: "preview.webp",
339
+ contentType: "image/webp",
340
+ bytes: new Uint8Array(previewBuffer)
341
+ }
342
+ };
343
+ }
344
+ function formatOptions(format, quality) {
345
+ switch (format) {
346
+ case "jpeg":
347
+ return { quality };
348
+ case "png":
349
+ return {};
350
+ case "webp":
351
+ default:
352
+ return { quality };
353
+ }
354
+ }
355
+ function extensionForFormat(format) {
356
+ return format === "jpeg" ? "jpg" : format;
357
+ }
358
+ function contentTypeForFormat(format) {
359
+ switch (format) {
360
+ case "jpeg":
361
+ return "image/jpeg";
362
+ case "png":
363
+ return "image/png";
364
+ case "webp":
365
+ default:
366
+ return "image/webp";
367
+ }
368
+ }
369
+
370
+ // src/ingest/pipeline/manifestBuilder.ts
371
+ function buildManifest(options) {
372
+ const minZoom = options.levels[0]?.z ?? 0;
373
+ const maxZoom = options.levels[options.levels.length - 1]?.z ?? 0;
374
+ return createManifest({
375
+ id: options.id,
376
+ source: {
377
+ type: options.sourceType,
378
+ originalFilename: options.originalFilename,
379
+ page: options.page,
380
+ width: options.width,
381
+ height: options.height,
382
+ mimeType: options.mimeType
383
+ },
384
+ coordinateSpace: {
385
+ normalized: true,
386
+ width: options.width,
387
+ height: options.height
388
+ },
389
+ tiles: {
390
+ tileSize: options.tileSize,
391
+ format: options.tileFormat,
392
+ minZoom,
393
+ maxZoom,
394
+ pathTemplate: withBaseUrl(options.baseUrl, `tiles/{z}/{x}/{y}.${options.tileFormat === "jpeg" ? "jpg" : options.tileFormat}`),
395
+ levels: options.levels
396
+ },
397
+ view: {
398
+ defaultCenter: [0.5, 0.5],
399
+ defaultZoom: 1,
400
+ minZoom: 0,
401
+ maxZoom: Math.max(maxZoom + 2, 6)
402
+ },
403
+ overlays: options.inlineOverlays || options.overlayUrl ? {
404
+ inline: options.inlineOverlays,
405
+ url: options.overlayUrl ? withBaseUrl(options.baseUrl, options.overlayUrl) : void 0
406
+ } : void 0,
407
+ assets: options.previewPath ? {
408
+ preview: withBaseUrl(options.baseUrl, options.previewPath)
409
+ } : void 0,
410
+ metadata: {
411
+ title: options.title,
412
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
413
+ }
414
+ });
415
+ }
416
+ function withBaseUrl(baseUrl, path) {
417
+ if (!baseUrl) {
418
+ return path;
419
+ }
420
+ if (/^https?:\/\//.test(baseUrl)) {
421
+ return new URL(path.replace(/^\//, ""), ensureTrailingSlash2(baseUrl)).toString();
422
+ }
423
+ return joinRelativeUrl2(baseUrl, path);
424
+ }
425
+ function ensureTrailingSlash2(baseUrl) {
426
+ return baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
427
+ }
428
+ function joinRelativeUrl2(baseUrl, path) {
429
+ const normalizedBase = ensureLeadingSlash2(stripTrailingSlash2(baseUrl));
430
+ const normalizedPath = stripLeadingSlash2(path);
431
+ if (!normalizedPath) {
432
+ return normalizedBase || "/";
433
+ }
434
+ return normalizedBase ? `${normalizedBase}/${normalizedPath}` : `/${normalizedPath}`;
435
+ }
436
+ function stripLeadingSlash2(value) {
437
+ return value.replace(/^\/+/, "");
438
+ }
439
+ function stripTrailingSlash2(value) {
440
+ return value.replace(/\/+$/, "");
441
+ }
442
+ function ensureLeadingSlash2(value) {
443
+ if (!value) {
444
+ return "";
445
+ }
446
+ return value.startsWith("/") ? value : `/${value}`;
447
+ }
448
+
449
+ // src/ingest/pipeline/writeArtifacts.ts
450
+ async function writeArtifacts(adapter, manifest, files) {
451
+ const uploaded = [];
452
+ for (const file of files) {
453
+ if (file.kind === "tile") {
454
+ const match = file.path.match(/^tiles\/(\d+)\/(\d+)\/(\d+)\.[^.]+$/);
455
+ if (!match) {
456
+ throw new Error(`Invalid tile path: ${file.path}`);
457
+ }
458
+ uploaded.push(
459
+ await adapter.writeTile({
460
+ z: Number(match[1]),
461
+ x: Number(match[2]),
462
+ y: Number(match[3]),
463
+ ext: file.path.split(".").pop() ?? "bin",
464
+ bytes: file.bytes,
465
+ contentType: file.contentType
466
+ })
467
+ );
468
+ continue;
469
+ }
470
+ if (file.kind === "manifest") {
471
+ uploaded.push(
472
+ await adapter.writeManifest({
473
+ path: file.path,
474
+ bytes: file.bytes,
475
+ contentType: "application/json"
476
+ })
477
+ );
478
+ continue;
479
+ }
480
+ if (!adapter.writeAsset) {
481
+ throw new Error(`Storage adapter does not support writing ${file.kind} assets.`);
482
+ }
483
+ uploaded.push(
484
+ await adapter.writeAsset({
485
+ kind: file.kind,
486
+ path: file.path,
487
+ bytes: file.bytes,
488
+ contentType: file.contentType
489
+ })
490
+ );
491
+ }
492
+ const storage = await adapter.finalize({
493
+ manifest,
494
+ artifacts: uploaded
495
+ });
496
+ return {
497
+ uploaded,
498
+ storage
499
+ };
500
+ }
501
+
502
+ // src/ingest/ingestImage.ts
503
+ async function ingestImage(options) {
504
+ const inspected = await inspectInput(options.input);
505
+ const normalized = await normalizeImage({
506
+ bytes: inspected.bytes,
507
+ maxDimension: options.maxDimension ?? 12288,
508
+ background: options.background ?? "#ffffff"
509
+ });
510
+ return ingestRasterizedImage(normalized, {
511
+ common: options,
512
+ id: options.id ?? defaultId(inspected.originalFilename ?? "image"),
513
+ title: options.title,
514
+ sourceType: "image",
515
+ originalFilename: inspected.originalFilename,
516
+ mimeType: normalized.mimeType
517
+ });
518
+ }
519
+ async function ingestRasterizedImage(normalized, input) {
520
+ const tileSize = input.common.tileSize ?? 256;
521
+ const tileFormat = input.common.tileFormat ?? "webp";
522
+ const tileQuality = input.common.tileQuality ?? 92;
523
+ const storage = input.common.storage ?? memoryStorageAdapter();
524
+ const pyramid = await buildTilePyramid({
525
+ image: normalized.bytes,
526
+ width: normalized.width,
527
+ height: normalized.height,
528
+ tileSize,
529
+ format: tileFormat,
530
+ quality: tileQuality
531
+ });
532
+ const overlayPayload = await resolveOverlayPayload(input.common.overlays);
533
+ const manifest = buildManifest({
534
+ id: input.id,
535
+ title: input.title,
536
+ sourceType: input.sourceType,
537
+ originalFilename: input.originalFilename,
538
+ page: input.page,
539
+ width: normalized.width,
540
+ height: normalized.height,
541
+ mimeType: input.mimeType ?? normalized.mimeType,
542
+ tileSize,
543
+ tileFormat,
544
+ levels: pyramid.levels,
545
+ baseUrl: input.common.baseUrl,
546
+ inlineOverlays: overlayPayload.inline,
547
+ overlayUrl: overlayPayload.url,
548
+ previewPath: pyramid.preview.path
549
+ });
550
+ const files = [...pyramid.tiles, pyramid.preview];
551
+ if (overlayPayload.file) {
552
+ files.push(overlayPayload.file);
553
+ }
554
+ files.push({
555
+ kind: "manifest",
556
+ path: "manifest.json",
557
+ contentType: "application/json",
558
+ bytes: new TextEncoder().encode(JSON.stringify(manifest, null, 2))
559
+ });
560
+ const { uploaded, storage: storageResult } = await writeArtifacts(storage, manifest, files);
561
+ return {
562
+ manifest,
563
+ width: normalized.width,
564
+ height: normalized.height,
565
+ tileCount: pyramid.tiles.length,
566
+ files,
567
+ uploaded,
568
+ warnings: [],
569
+ storage: storageResult
570
+ };
571
+ }
572
+ async function resolveOverlayPayload(input) {
573
+ if (!input) {
574
+ return {};
575
+ }
576
+ if (typeof input === "string") {
577
+ return {
578
+ url: input
579
+ };
580
+ }
581
+ const bytes = new TextEncoder().encode(JSON.stringify(input, null, 2));
582
+ if (bytes.byteLength < 64 * 1024) {
583
+ return {
584
+ inline: input
585
+ };
586
+ }
587
+ return {
588
+ url: "regions.json",
589
+ file: {
590
+ kind: "overlay",
591
+ path: "regions.json",
592
+ contentType: "application/json",
593
+ bytes
594
+ }
595
+ };
596
+ }
597
+ function defaultId(seed) {
598
+ const safe = seed.replace(/\.[^.]+$/, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
599
+ return safe || randomUUID();
600
+ }
601
+
602
+ // src/ingest/ingestPdf.ts
603
+ async function ingestPdf(options) {
604
+ const inspected = await inspectInput(options.input);
605
+ const page = options.page ?? 1;
606
+ const rasterized = await rasterizePdf({
607
+ bytes: inspected.bytes,
608
+ page,
609
+ maxDimension: options.maxDimension ?? 12288,
610
+ rasterDpi: options.rasterDpi,
611
+ background: options.background ?? "#ffffff"
612
+ });
613
+ return ingestRasterizedImage(rasterized, {
614
+ common: options,
615
+ id: options.id ?? defaultId2(inspected.originalFilename ?? "pdf"),
616
+ title: options.title,
617
+ sourceType: "pdf",
618
+ originalFilename: inspected.originalFilename,
619
+ mimeType: "application/pdf",
620
+ page
621
+ });
622
+ }
623
+ function defaultId2(seed) {
624
+ const safe = seed.replace(/\.[^.]+$/, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
625
+ return safe || randomUUID();
626
+ }
627
+ function localStorageAdapter(options) {
628
+ const baseDir = resolve(options.baseDir);
629
+ const manifestName = options.manifestName ?? "manifest.json";
630
+ const artifacts = [];
631
+ let cleaned = false;
632
+ const ensureParent = async (filePath) => {
633
+ await mkdir(dirname(filePath), { recursive: true });
634
+ };
635
+ const ensureClean = async () => {
636
+ if (!options.clean || cleaned) {
637
+ return;
638
+ }
639
+ cleaned = true;
640
+ await rm(baseDir, { recursive: true, force: true });
641
+ };
642
+ const write = async (kind, relativePath, contentType, bytes) => {
643
+ await ensureClean();
644
+ const path = join(baseDir, relativePath);
645
+ await ensureParent(path);
646
+ await writeFile(path, bytes);
647
+ const artifact = {
648
+ kind,
649
+ path,
650
+ contentType,
651
+ size: bytes.byteLength
652
+ };
653
+ artifacts.push(artifact);
654
+ return artifact;
655
+ };
656
+ return {
657
+ async writeTile(args) {
658
+ return write(
659
+ "tile",
660
+ `tiles/${args.z}/${args.x}/${args.y}.${args.ext}`,
661
+ args.contentType,
662
+ args.bytes
663
+ );
664
+ },
665
+ async writeManifest(args) {
666
+ return write("manifest", manifestName, args.contentType, args.bytes);
667
+ },
668
+ async writeAsset(args) {
669
+ return write(args.kind, args.path, args.contentType, args.bytes);
670
+ },
671
+ async finalize(_args) {
672
+ return {
673
+ artifacts: [...artifacts]
674
+ };
675
+ }
676
+ };
677
+ }
678
+
679
+ // src/ingest/storage/s3Compatible.ts
680
+ function s3CompatibleStorageAdapter(options) {
681
+ const prefix = normalizePrefix(options.prefix);
682
+ const artifacts = [];
683
+ const upload = async (kind, relativePath, contentType, bytes, cacheControl) => {
684
+ const key = `${prefix}${relativePath}`;
685
+ const result = await options.putObject({
686
+ key,
687
+ body: bytes,
688
+ contentType,
689
+ cacheControl
690
+ });
691
+ const artifact = {
692
+ kind,
693
+ path: key,
694
+ contentType,
695
+ size: bytes.byteLength,
696
+ url: result?.url ?? (options.baseUrl ? `${normalizeBaseUrl(options.baseUrl)}${key}` : void 0)
697
+ };
698
+ artifacts.push(artifact);
699
+ return artifact;
700
+ };
701
+ return {
702
+ async writeTile(args) {
703
+ return upload(
704
+ "tile",
705
+ `tiles/${args.z}/${args.x}/${args.y}.${args.ext}`,
706
+ args.contentType,
707
+ args.bytes,
708
+ "public, max-age=31536000, immutable"
709
+ );
710
+ },
711
+ async writeManifest(args) {
712
+ return upload("manifest", args.path, args.contentType, args.bytes, "public, max-age=60");
713
+ },
714
+ async writeAsset(args) {
715
+ const cacheControl = args.kind === "preview" ? "public, max-age=31536000, immutable" : "public, max-age=60";
716
+ return upload(args.kind, args.path, args.contentType, args.bytes, cacheControl);
717
+ },
718
+ async finalize(_args) {
719
+ return {
720
+ artifacts: [...artifacts],
721
+ baseUrl: options.baseUrl
722
+ };
723
+ }
724
+ };
725
+ }
726
+ function normalizePrefix(prefix) {
727
+ if (!prefix) {
728
+ return "";
729
+ }
730
+ return prefix.endsWith("/") ? prefix : `${prefix}/`;
731
+ }
732
+ function normalizeBaseUrl(baseUrl) {
733
+ return baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
734
+ }
735
+
736
+ export { createManifest, ingestImage, ingestPdf, localStorageAdapter, memoryStorageAdapter, parseManifest, resolveTileUrl, s3CompatibleStorageAdapter };
737
+ //# sourceMappingURL=index.js.map
738
+ //# sourceMappingURL=index.js.map