@papyrus-sdk/engine-native 0.2.16 → 0.2.18

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.js CHANGED
@@ -32,6 +32,57 @@ var import_NativeViewManagerAdapter = require("expo-modules-core/src/NativeViewM
32
32
  var import_requireNativeModule = require("expo-modules-core/src/requireNativeModule");
33
33
  var import_core = require("@papyrus-sdk/core");
34
34
  var import_types = require("@papyrus-sdk/types");
35
+
36
+ // documentType.ts
37
+ var parseDataUri = (value) => {
38
+ const match = /^data:([^;,]+)?(;base64)?,(.*)$/.exec(value);
39
+ if (!match) return null;
40
+ return {
41
+ mime: match[1] ?? "",
42
+ isBase64: Boolean(match[2]),
43
+ data: match[3] ?? ""
44
+ };
45
+ };
46
+ var typeFromExtension = (value) => {
47
+ const clean = value.split("?")[0].split("#")[0].toLowerCase();
48
+ const extension = clean.includes(".") ? clean.split(".").pop() : void 0;
49
+ if (extension === "epub") return "epub";
50
+ if (extension === "txt") return "text";
51
+ if (extension === "pdf") return "pdf";
52
+ if (extension === "cbz" || extension === "cbr") return "comic";
53
+ return null;
54
+ };
55
+ var inferComicFormat = (source) => {
56
+ const candidate = typeof source === "string" ? source : typeof source === "object" && source !== null && "uri" in source ? source.uri : "";
57
+ const dataUri = parseDataUri(candidate);
58
+ const mime = dataUri?.mime.toLowerCase() ?? "";
59
+ if (mime.includes("rar") || /\.cbr(?:$|[?#])/i.test(candidate)) {
60
+ return "cbr";
61
+ }
62
+ return "cbz";
63
+ };
64
+ var resolveComicFormat = (source, explicitFormat) => explicitFormat ?? inferComicFormat(source);
65
+ var inferDocumentType = (source) => {
66
+ if (typeof source === "string") {
67
+ const dataUri = parseDataUri(source);
68
+ if (dataUri?.mime) {
69
+ const mime = dataUri.mime.toLowerCase();
70
+ if (mime.includes("epub")) return "epub";
71
+ if (mime.includes("comicbook") || mime.includes("zip") || mime.includes("rar")) {
72
+ return "comic";
73
+ }
74
+ if (mime.includes("text")) return "text";
75
+ if (mime.includes("pdf")) return "pdf";
76
+ }
77
+ return typeFromExtension(source) ?? "pdf";
78
+ }
79
+ if (typeof source === "object" && source !== null && "uri" in source) {
80
+ return typeFromExtension(source.uri) ?? "pdf";
81
+ }
82
+ return "pdf";
83
+ };
84
+
85
+ // index.ts
35
86
  var MODULE_NAME = "PapyrusNativeEngine";
36
87
  var BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
37
88
  var BASE64_LOOKUP = (() => {
@@ -42,7 +93,7 @@ var BASE64_LOOKUP = (() => {
42
93
  }
43
94
  return table;
44
95
  })();
45
- var parseDataUri = (value) => {
96
+ var parseDataUri2 = (value) => {
46
97
  const match = /^data:([^;,]+)?(;base64)?,(.*)$/.exec(value);
47
98
  if (!match) return null;
48
99
  return {
@@ -51,7 +102,7 @@ var parseDataUri = (value) => {
51
102
  data: match[3] ?? ""
52
103
  };
53
104
  };
54
- var looksLikeUri = (value) => value.startsWith("http://") || value.startsWith("https://") || value.startsWith("/") || value.startsWith("./") || value.startsWith("../") || value.startsWith("file://");
105
+ var looksLikeUri = (value) => value.startsWith("http://") || value.startsWith("https://") || value.startsWith("/") || value.startsWith("./") || value.startsWith("../") || value.startsWith("file://") || value.startsWith("content://");
55
106
  var isLikelyBase64 = (value) => {
56
107
  if (looksLikeUri(value)) return false;
57
108
  if (value.includes(".")) return false;
@@ -59,6 +110,7 @@ var isLikelyBase64 = (value) => {
59
110
  return /^[A-Za-z0-9+/=]+$/.test(value);
60
111
  };
61
112
  var isHttpUri = (value) => value.startsWith("http://") || value.startsWith("https://");
113
+ var isLocalUri = (value) => value.startsWith("content://") || value.startsWith("file://");
62
114
  var decodeBase64 = (value) => {
63
115
  const clean = value.replace(/[^A-Za-z0-9+/=]/g, "");
64
116
  const padding = clean.endsWith("==") ? 2 : clean.endsWith("=") ? 1 : 0;
@@ -102,33 +154,7 @@ var encodeBase64 = (bytes) => {
102
154
  return output;
103
155
  };
104
156
  var isLoadRequest = (input) => typeof input === "object" && input !== null && "source" in input && "type" in input;
105
- var normalizeLoadInput = (input) => isLoadRequest(input) ? { source: input.source, type: input.type } : { source: input };
106
- var inferDocumentType = (source) => {
107
- if (typeof source === "string") {
108
- const dataUri = parseDataUri(source);
109
- if (dataUri?.mime) {
110
- const mime = dataUri.mime.toLowerCase();
111
- if (mime.includes("epub")) return "epub";
112
- if (mime.includes("text")) return "text";
113
- if (mime.includes("pdf")) return "pdf";
114
- }
115
- const clean = source.split("?")[0].split("#")[0];
116
- const ext = clean.includes(".") ? clean.split(".").pop()?.toLowerCase() : void 0;
117
- if (ext === "epub") return "epub";
118
- if (ext === "txt") return "text";
119
- if (ext === "pdf") return "pdf";
120
- return "pdf";
121
- }
122
- if (typeof source === "object" && source !== null && "uri" in source) {
123
- const uri = source.uri;
124
- const clean = uri.split("?")[0].split("#")[0];
125
- const ext = clean.includes(".") ? clean.split(".").pop()?.toLowerCase() : void 0;
126
- if (ext === "epub") return "epub";
127
- if (ext === "txt") return "text";
128
- if (ext === "pdf") return "pdf";
129
- }
130
- return "pdf";
131
- };
157
+ var normalizeLoadInput = (input) => isLoadRequest(input) ? { source: input.source, type: input.type, format: input.format } : { source: input };
132
158
  var normalizeNativeDestination = (dest) => {
133
159
  if (!dest) return null;
134
160
  if (typeof dest === "string") {
@@ -151,12 +177,12 @@ var resolveNativeModule = () => {
151
177
  };
152
178
  var resolvePapyrusPageView = () => {
153
179
  try {
154
- return (0, import_NativeViewManagerAdapter.requireNativeViewManager)(
180
+ return (0, import_react_native.requireNativeComponent)(
155
181
  "PapyrusPageView"
156
182
  );
157
183
  } catch {
158
184
  try {
159
- return (0, import_react_native.requireNativeComponent)(
185
+ return (0, import_NativeViewManagerAdapter.requireNativeViewManager)(
160
186
  "PapyrusPageView"
161
187
  );
162
188
  } catch {
@@ -167,12 +193,12 @@ var resolvePapyrusPageView = () => {
167
193
  var resolvePapyrusPdfViewerView = () => {
168
194
  const componentName = import_react_native.Platform.OS === "ios" ? "PapyrusPdfDocumentView" : "PapyrusPdfViewerView";
169
195
  try {
170
- return (0, import_NativeViewManagerAdapter.requireNativeViewManager)(
196
+ return (0, import_react_native.requireNativeComponent)(
171
197
  componentName
172
198
  );
173
199
  } catch {
174
200
  try {
175
- return (0, import_react_native.requireNativeComponent)(
201
+ return (0, import_NativeViewManagerAdapter.requireNativeViewManager)(
176
202
  componentName
177
203
  );
178
204
  } catch {
@@ -333,7 +359,7 @@ var NativeDocumentEngine = class extends import_core.BaseDocumentEngine {
333
359
  }
334
360
  async normalizeSource(source) {
335
361
  if (typeof source === "string") {
336
- const dataUri = parseDataUri(source);
362
+ const dataUri = parseDataUri2(source);
337
363
  if (dataUri?.isBase64) {
338
364
  return { data: decodeBase64(dataUri.data) };
339
365
  }
@@ -371,8 +397,8 @@ var NativeDocumentEngine = class extends import_core.BaseDocumentEngine {
371
397
  }
372
398
  };
373
399
  var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
374
- constructor() {
375
- super(...arguments);
400
+ constructor(options = {}) {
401
+ super();
376
402
  this.bridge = null;
377
403
  this.ready = false;
378
404
  this.requestId = 0;
@@ -384,6 +410,14 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
384
410
  this.zoom = 1;
385
411
  this.rotation = 0;
386
412
  this.outline = [];
413
+ this.webViewRuntimeSource = options.webViewRuntimeSource;
414
+ this.webViewRuntimeConfig = options.webViewRuntimeConfig;
415
+ }
416
+ getWebViewRuntimeSource() {
417
+ return this.webViewRuntimeSource;
418
+ }
419
+ getWebViewRuntimeConfig() {
420
+ return this.webViewRuntimeConfig;
387
421
  }
388
422
  getRenderTargetType() {
389
423
  return "webview";
@@ -401,6 +435,14 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
401
435
  return;
402
436
  }
403
437
  if (!message) return;
438
+ if (message.type === "asset-request") {
439
+ void this.handleAssetRequest(message);
440
+ return;
441
+ }
442
+ if (message.type === "file-chunk-request") {
443
+ void this.handleFileChunkRequest(message);
444
+ return;
445
+ }
404
446
  if (message.type === "ready") {
405
447
  this.ready = true;
406
448
  this.readyResolvers.forEach((resolve) => resolve());
@@ -466,8 +508,73 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
466
508
  console.warn("[Papyrus WebView] Unknown message", message);
467
509
  }
468
510
  }
511
+ async handleAssetRequest(message) {
512
+ const bridge = this.bridge;
513
+ if (!bridge) return;
514
+ try {
515
+ const response = await fetch(message.url);
516
+ if (!response.ok) {
517
+ throw new Error(`status ${response.status}`);
518
+ }
519
+ const data = message.encoding === "text" ? await response.text() : `data:application/wasm;base64,${encodeBase64(
520
+ new Uint8Array(await response.arrayBuffer())
521
+ )}`;
522
+ bridge.postMessage(
523
+ JSON.stringify({
524
+ type: "asset-response",
525
+ id: message.id,
526
+ ok: true,
527
+ data
528
+ })
529
+ );
530
+ } catch (error) {
531
+ const reason = error instanceof Error ? error.message : String(error);
532
+ bridge.postMessage(
533
+ JSON.stringify({
534
+ type: "asset-response",
535
+ id: message.id,
536
+ ok: false,
537
+ error: reason
538
+ })
539
+ );
540
+ }
541
+ }
542
+ async handleFileChunkRequest(message) {
543
+ const bridge = this.bridge;
544
+ if (!bridge) return;
545
+ try {
546
+ const nativeModule = resolveNativeModule();
547
+ if (!nativeModule?.readFileChunk) {
548
+ throw new Error("Leitura nativa de arquivos n\xE3o est\xE1 dispon\xEDvel");
549
+ }
550
+ const result = await nativeModule.readFileChunk(
551
+ message.uri,
552
+ message.offset,
553
+ message.length
554
+ );
555
+ bridge.postMessage(
556
+ JSON.stringify({
557
+ type: "file-chunk-response",
558
+ id: message.id,
559
+ ok: true,
560
+ data: result.data,
561
+ done: result.done
562
+ })
563
+ );
564
+ } catch (error) {
565
+ const reason = error instanceof Error ? error.message : String(error);
566
+ bridge.postMessage(
567
+ JSON.stringify({
568
+ type: "file-chunk-response",
569
+ id: message.id,
570
+ ok: false,
571
+ error: reason
572
+ })
573
+ );
574
+ }
575
+ }
469
576
  async load(input) {
470
- const { source, type } = normalizeLoadInput(input);
577
+ const { source, type, format } = normalizeLoadInput(input);
471
578
  const resolvedType = type ?? inferDocumentType(source);
472
579
  if (resolvedType === "pdf") {
473
580
  throw new Error(
@@ -480,7 +587,8 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
480
587
  );
481
588
  const response = await this.request("load", {
482
589
  type: resolvedType,
483
- source: payloadSource
590
+ source: payloadSource,
591
+ ...resolvedType === "comic" ? { format: resolveComicFormat(source, format) } : {}
484
592
  });
485
593
  if (typeof response?.pageCount === "number")
486
594
  this.pageCount = response.pageCount;
@@ -530,6 +638,11 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
530
638
  { pageIndex }
531
639
  );
532
640
  }
641
+ async getPagePreview(pageIndex) {
642
+ return await this.request("get-page-preview", {
643
+ pageIndex
644
+ });
645
+ }
533
646
  async searchText(query) {
534
647
  return await this.request("search-text", { query });
535
648
  }
@@ -582,7 +695,7 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
582
695
  await this.ensureReady();
583
696
  const id = `${Date.now()}-${this.requestId++}`;
584
697
  return new Promise((resolve, reject) => {
585
- const timeoutMs = kind === "load" ? 18e4 : 8e3;
698
+ const timeoutMs = kind === "load" ? 18e4 : kind === "get-page-preview" ? 3e4 : 8e3;
586
699
  const timeoutId = setTimeout(() => {
587
700
  this.pending.delete(id);
588
701
  reject(new Error(`[Papyrus] WebView response timeout: ${kind}`));
@@ -602,7 +715,7 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
602
715
  }
603
716
  async normalizeRuntimeSource(type, source) {
604
717
  if (typeof source === "string") {
605
- const dataUri = parseDataUri(source);
718
+ const dataUri = parseDataUri2(source);
606
719
  if (dataUri) {
607
720
  if (dataUri.isBase64) {
608
721
  return {
@@ -619,6 +732,9 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
619
732
  const fetched = await this.fetchRemoteSource(type, source);
620
733
  if (fetched) return fetched;
621
734
  }
735
+ if (isLocalUri(source)) {
736
+ return await this.fetchLocalSource(type, source);
737
+ }
622
738
  return { kind: "uri", uri: source };
623
739
  }
624
740
  if (isLikelyBase64(source)) {
@@ -635,6 +751,9 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
635
751
  const fetched = await this.fetchRemoteSource(type, uri);
636
752
  if (fetched) return fetched;
637
753
  }
754
+ if (isLocalUri(uri)) {
755
+ return await this.fetchLocalSource(type, uri);
756
+ }
638
757
  return { kind: "uri", uri };
639
758
  }
640
759
  if (this.isDataSource(source)) {
@@ -666,11 +785,35 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
666
785
  const buffer = await this.readResponseBuffer(response);
667
786
  return { kind: "base64", data: encodeBase64(new Uint8Array(buffer)) };
668
787
  }
788
+ if (type === "comic") {
789
+ const buffer = await this.readResponseBuffer(response);
790
+ return { kind: "base64", data: encodeBase64(new Uint8Array(buffer)) };
791
+ }
669
792
  return null;
670
793
  } catch {
671
794
  return null;
672
795
  }
673
796
  }
797
+ async fetchLocalSource(type, uri) {
798
+ if (type === "epub" || type === "comic") {
799
+ return { kind: "uri", uri };
800
+ }
801
+ try {
802
+ const response = await fetch(uri);
803
+ if (!response.ok && response.status !== 0) {
804
+ throw new Error(`status ${response.status}`);
805
+ }
806
+ if (type === "text") {
807
+ return { kind: "text", text: await response.text() };
808
+ }
809
+ throw new Error(`tipo n\xE3o suportado: ${type}`);
810
+ } catch (error) {
811
+ const reason = error instanceof Error ? `: ${error.message}` : "";
812
+ throw new Error(
813
+ `[WebViewDocumentEngine] N\xE3o foi poss\xEDvel ler o arquivo local ${uri}${reason}`
814
+ );
815
+ }
816
+ }
674
817
  async readResponseBuffer(response) {
675
818
  try {
676
819
  return await response.arrayBuffer();
@@ -695,12 +838,18 @@ var WebViewDocumentEngine = class extends import_core.BaseDocumentEngine {
695
838
  }
696
839
  };
697
840
  var MobileDocumentEngine = class extends import_core.BaseDocumentEngine {
698
- constructor() {
841
+ constructor(options = {}) {
699
842
  super();
700
843
  this.pdfEngine = new NativeDocumentEngine();
701
- this.webEngine = new WebViewDocumentEngine();
844
+ this.webEngine = new WebViewDocumentEngine(options);
702
845
  this.activeEngine = this.pdfEngine;
703
846
  }
847
+ getWebViewRuntimeSource() {
848
+ return this.webEngine.getWebViewRuntimeSource();
849
+ }
850
+ getWebViewRuntimeConfig() {
851
+ return this.webEngine.getWebViewRuntimeConfig();
852
+ }
704
853
  getRenderTargetType() {
705
854
  return this.activeEngine.getRenderTargetType?.() ?? "canvas";
706
855
  }
@@ -714,10 +863,14 @@ var MobileDocumentEngine = class extends import_core.BaseDocumentEngine {
714
863
  this.webEngine.handleMessage(data);
715
864
  }
716
865
  async load(input) {
717
- const { source, type } = normalizeLoadInput(input);
866
+ const { source, type, format } = normalizeLoadInput(input);
718
867
  const resolvedType = type ?? inferDocumentType(source);
719
868
  this.activeEngine = resolvedType === "pdf" ? this.pdfEngine : this.webEngine;
720
- await this.activeEngine.load({ type: resolvedType, source });
869
+ await this.activeEngine.load({
870
+ type: resolvedType,
871
+ source,
872
+ ...resolvedType === "comic" && format ? { format } : {}
873
+ });
721
874
  }
722
875
  getPageCount() {
723
876
  return this.activeEngine.getPageCount();
@@ -752,6 +905,10 @@ var MobileDocumentEngine = class extends import_core.BaseDocumentEngine {
752
905
  async getPageDimensions(pageIndex) {
753
906
  return await this.activeEngine.getPageDimensions(pageIndex);
754
907
  }
908
+ async getPagePreview(pageIndex) {
909
+ const engine = this.activeEngine;
910
+ return await engine.getPagePreview?.(pageIndex) ?? null;
911
+ }
755
912
  async searchText(query) {
756
913
  if (typeof this.activeEngine.searchText === "function") {
757
914
  return await this.activeEngine.searchText(query);