@pretextbook/import 0.7.0 → 0.9.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.
package/README.md CHANGED
@@ -187,3 +187,40 @@ and use a fixed configuration.
187
187
  confirm). Its source-selection step — format dropdown, main-document picker,
188
188
  and per-file attach controls — appears whenever the upload leaves a real choice
189
189
  open, and is always reachable from the review step.
190
+
191
+ ### Choosing the default import style
192
+
193
+ A LaTeX or Markdown upload can be imported two ways: `"converted"` (the
194
+ generated PreTeXt) or `"native"` (the cleaned original source, unconverted).
195
+ Each host picks which one the review step starts on — the VS Code extension
196
+ reads the `pretext-tools.import.defaultMode` setting; another host might read
197
+ an account preference:
198
+
199
+ ```tsx
200
+ <ImportWizard
201
+ defaultImportMode="native" // starts on "Keep as LaTeX"; user can still switch
202
+ onImportModeChange={(mode) => remember(mode)}
203
+ onConfirm={handleConfirm}
204
+ />
205
+ ```
206
+
207
+ Pass `lockImportMode` alongside it to hide the chooser entirely and import in
208
+ that one style — for hosts that only support one.
209
+
210
+ A PreTeXt upload has no native alternative, so the chooser is hidden and the
211
+ mode handed to `onConfirm` is always `"converted"`, whatever the default said.
212
+ Outside the wizard the same rules are available directly:
213
+
214
+ ```ts
215
+ import {
216
+ DEFAULT_IMPORT_MODE, // "converted"
217
+ hasNativeImportMode, // does this result carry a native alternative?
218
+ resolveImportMode, // preference + result → the mode that really applies
219
+ filesForImportMode,
220
+ assetsForImportMode,
221
+ projectForImportMode,
222
+ } from "@pretextbook/import";
223
+
224
+ const mode = resolveImportMode(result, preferredMode);
225
+ const files = filesForImportMode(result, mode);
226
+ ```
@@ -1 +1 @@
1
- "use strict";const n=require("./upload-CGxfSSDN.cjs");function f(e){if(e.type!=="result"||"pretextError"in e.result)return[];const t=e.result,o=new Set,s=r=>{const c=r?.buffer;c instanceof ArrayBuffer&&o.add(c)};return Object.values(t.assets??{}).forEach(s),Object.values(t.outputAssets??{}).forEach(s),t.project?.assets?.forEach(r=>s(r.data)),t.nativeProject?.assets?.forEach(r=>s(r.data)),[...o]}function u(e){self.postMessage(e,f(e))}self.onmessage=e=>{const t=e.data;if(t?.type!=="convert")return;const{requestId:o,files:s,assets:r,options:c}=t;try{const a=n.importProjectFromFiles(s,{...c,assets:r});u({type:"result",requestId:o,result:a})}catch(a){u({type:"error",requestId:o,message:a instanceof Error?a.message:"An unexpected error occurred."})}};
1
+ "use strict";const n=require("./upload-BtS22hIH.cjs");function f(e){if(e.type!=="result"||"pretextError"in e.result)return[];const t=e.result,o=new Set,s=r=>{const c=r?.buffer;c instanceof ArrayBuffer&&o.add(c)};return Object.values(t.assets??{}).forEach(s),Object.values(t.outputAssets??{}).forEach(s),t.project?.assets?.forEach(r=>s(r.data)),t.nativeProject?.assets?.forEach(r=>s(r.data)),[...o]}function u(e){self.postMessage(e,f(e))}self.onmessage=e=>{const t=e.data;if(t?.type!=="convert")return;const{requestId:o,files:s,assets:r,options:c}=t;try{const a=n.importProjectFromFiles(s,{...c,assets:r});u({type:"result",requestId:o,result:a})}catch(a){u({type:"error",requestId:o,message:a instanceof Error?a.message:"An unexpected error occurred."})}};
@@ -1,4 +1,4 @@
1
- import { T as n } from "./upload-BBHV4rXJ.js";
1
+ import { T as n } from "./upload-BmErkg8I.js";
2
2
  function u(e) {
3
3
  if (e.type !== "result" || "pretextError" in e.result)
4
4
  return [];
@@ -0,0 +1,122 @@
1
+ import { X as p, a4 as h } from "./upload-BmErkg8I.js";
2
+ function u(e, t) {
3
+ const o = e.length === 0 ? [] : e.split(`
4
+ `), i = t.length === 0 ? [] : t.split(`
5
+ `);
6
+ if (o.length + i.length > d)
7
+ return [
8
+ ...o.map(
9
+ (s, l) => ({ op: "remove", text: s, beforeLine: l + 1 })
10
+ ),
11
+ ...i.map((s, l) => ({ op: "add", text: s, afterLine: l + 1 }))
12
+ ];
13
+ const a = Array.from(
14
+ { length: o.length + 1 },
15
+ () => new Array(i.length + 1).fill(0)
16
+ );
17
+ for (let s = o.length - 1; s >= 0; s--)
18
+ for (let l = i.length - 1; l >= 0; l--)
19
+ a[s][l] = o[s] === i[l] ? a[s + 1][l + 1] + 1 : Math.max(a[s + 1][l], a[s][l + 1]);
20
+ const c = [];
21
+ let n = 0, r = 0;
22
+ for (; n < o.length && r < i.length; )
23
+ o[n] === i[r] ? (c.push({
24
+ op: "keep",
25
+ text: o[n],
26
+ beforeLine: n + 1,
27
+ afterLine: r + 1
28
+ }), n++, r++) : a[n + 1][r] >= a[n][r + 1] ? (c.push({ op: "remove", text: o[n], beforeLine: n + 1 }), n++) : (c.push({ op: "add", text: i[r], afterLine: r + 1 }), r++);
29
+ for (; n < o.length; )
30
+ c.push({ op: "remove", text: o[n], beforeLine: ++n });
31
+ for (; r < i.length; ) c.push({ op: "add", text: i[r], afterLine: ++r });
32
+ return c;
33
+ }
34
+ const d = 2e4;
35
+ function m(e) {
36
+ let t = 0, o = 0;
37
+ for (const i of e)
38
+ i.op === "add" ? t++ : i.op === "remove" && o++;
39
+ return { added: t, removed: o };
40
+ }
41
+ function v(e, t = 2) {
42
+ const o = e.map((n, r) => n.op === "keep" ? -1 : r).filter((n) => n >= 0);
43
+ if (o.length === 0) return [];
44
+ const i = [];
45
+ let a = Math.max(0, o[0] - t), c = Math.min(e.length - 1, o[0] + t);
46
+ for (const n of o.slice(1)) {
47
+ if (n - t <= c + 1) {
48
+ c = Math.min(e.length - 1, n + t);
49
+ continue;
50
+ }
51
+ i.push({ lines: e.slice(a, c + 1) }), a = Math.max(0, n - t), c = Math.min(e.length - 1, n + t);
52
+ }
53
+ return i.push({ lines: e.slice(a, c + 1) }), i;
54
+ }
55
+ function k(e, t = e.splitLevel) {
56
+ if (e.cleanChunks.length === 0) return [];
57
+ const o = p(e.cleanChunks, t), i = g(o), { pathByRef: a } = h(e.project, {
58
+ mainSourcePath: e.projectLayout.mainSourcePath,
59
+ publicationPath: e.projectLayout.publicationPath,
60
+ projectFilePath: e.projectLayout.projectFilePath,
61
+ includeScaffold: !e.projectLayout.preserved
62
+ }), c = [];
63
+ for (const n of e.project.divisions) {
64
+ const r = a[n.xmlId];
65
+ if (!r) continue;
66
+ const s = n.isRoot ? o.find((f) => f.kind === "preamble" || f.kind === "lead") : i.get(n.title);
67
+ if (!s) continue;
68
+ const l = u(s.before, s.after);
69
+ c.push({
70
+ path: r,
71
+ title: n.title,
72
+ before: s.before,
73
+ after: s.after,
74
+ stats: m(l),
75
+ hunks: v(l),
76
+ fixCount: s.fixes.length
77
+ });
78
+ }
79
+ return c.sort((n, r) => n.path.localeCompare(r.path));
80
+ }
81
+ function g(e) {
82
+ const t = /* @__PURE__ */ new Map();
83
+ for (const i of e)
84
+ i.kind !== "division" || !i.title || t.set(i.title, t.has(i.title) ? null : i);
85
+ const o = /* @__PURE__ */ new Map();
86
+ for (const [i, a] of t)
87
+ a && o.set(i, a);
88
+ return o;
89
+ }
90
+ const L = "converted";
91
+ function M(e) {
92
+ return e.nativeOutputFiles !== void 0;
93
+ }
94
+ function F(e, t = L) {
95
+ return t === "native" && !M(e) ? "converted" : t;
96
+ }
97
+ function b(e, t) {
98
+ return t === "native" ? e.nativeProject ?? e.project : e.project;
99
+ }
100
+ function x(e, t) {
101
+ return t === "converted" ? e.outputFiles : e.nativeOutputFiles ?? e.files;
102
+ }
103
+ function I(e, t) {
104
+ return t === "converted" ? e.outputAssets : e.assets;
105
+ }
106
+ function y(e) {
107
+ const t = e.action === "replace" || e.action === "rewrite" ? `replaced with \`${e.replacement}\`` : e.message ?? e.action, o = e.occurrences > 1 ? ` (x${e.occurrences})` : "";
108
+ return `[${e.severity}] ${e.macro}: ${t}${o}`;
109
+ }
110
+ export {
111
+ L as D,
112
+ I as a,
113
+ u as b,
114
+ m as c,
115
+ v as d,
116
+ x as e,
117
+ k as f,
118
+ y as g,
119
+ M as h,
120
+ b as p,
121
+ F as r
122
+ };
@@ -0,0 +1,3 @@
1
+ "use strict";const p=require("./upload-BtS22hIH.cjs");function h(e,t){const n=e.length===0?[]:e.split(`
2
+ `),i=t.length===0?[]:t.split(`
3
+ `);if(n.length+i.length>M)return[...n.map((s,f)=>({op:"remove",text:s,beforeLine:f+1})),...i.map((s,f)=>({op:"add",text:s,afterLine:f+1}))];const c=Array.from({length:n.length+1},()=>new Array(i.length+1).fill(0));for(let s=n.length-1;s>=0;s--)for(let f=i.length-1;f>=0;f--)c[s][f]=n[s]===i[f]?c[s+1][f+1]+1:Math.max(c[s+1][f],c[s][f+1]);const a=[];let o=0,r=0;for(;o<n.length&&r<i.length;)n[o]===i[r]?(a.push({op:"keep",text:n[o],beforeLine:o+1,afterLine:r+1}),o++,r++):c[o+1][r]>=c[o][r+1]?(a.push({op:"remove",text:n[o],beforeLine:o+1}),o++):(a.push({op:"add",text:i[r],afterLine:r+1}),r++);for(;o<n.length;)a.push({op:"remove",text:n[o],beforeLine:++o});for(;r<i.length;)a.push({op:"add",text:i[r],afterLine:++r});return a}const M=2e4;function u(e){let t=0,n=0;for(const i of e)i.op==="add"?t++:i.op==="remove"&&n++;return{added:t,removed:n}}function d(e,t=2){const n=e.map((o,r)=>o.op==="keep"?-1:r).filter(o=>o>=0);if(n.length===0)return[];const i=[];let c=Math.max(0,n[0]-t),a=Math.min(e.length-1,n[0]+t);for(const o of n.slice(1)){if(o-t<=a+1){a=Math.min(e.length-1,o+t);continue}i.push({lines:e.slice(c,a+1)}),c=Math.max(0,o-t),a=Math.min(e.length-1,o+t)}return i.push({lines:e.slice(c,a+1)}),i}function L(e,t=e.splitLevel){if(e.cleanChunks.length===0)return[];const n=p.mergeChunksAtLevel(e.cleanChunks,t),i=g(n),{pathByRef:c}=p.serializeProjectToFiles(e.project,{mainSourcePath:e.projectLayout.mainSourcePath,publicationPath:e.projectLayout.publicationPath,projectFilePath:e.projectLayout.projectFilePath,includeScaffold:!e.projectLayout.preserved}),a=[];for(const o of e.project.divisions){const r=c[o.xmlId];if(!r)continue;const s=o.isRoot?n.find(l=>l.kind==="preamble"||l.kind==="lead"):i.get(o.title);if(!s)continue;const f=h(s.before,s.after);a.push({path:r,title:o.title,before:s.before,after:s.after,stats:u(f),hunks:d(f),fixCount:s.fixes.length})}return a.sort((o,r)=>o.path.localeCompare(r.path))}function g(e){const t=new Map;for(const i of e)i.kind!=="division"||!i.title||t.set(i.title,t.has(i.title)?null:i);const n=new Map;for(const[i,c]of t)c&&n.set(i,c);return n}const m="converted";function v(e){return e.nativeOutputFiles!==void 0}function F(e,t=m){return t==="native"&&!v(e)?"converted":t}function I(e,t){return t==="native"?e.nativeProject??e.project:e.project}function j(e,t){return t==="converted"?e.outputFiles:e.nativeOutputFiles??e.files}function k(e,t){return t==="converted"?e.outputAssets:e.assets}function b(e){const t=e.action==="replace"||e.action==="rewrite"?`replaced with \`${e.replacement}\``:e.message??e.action,n=e.occurrences>1?` (x${e.occurrences})`:"";return`[${e.severity}] ${e.macro}: ${t}${n}`}exports.DEFAULT_IMPORT_MODE=m;exports.assetsForImportMode=k;exports.diffHunks=d;exports.diffLines=h;exports.diffStats=u;exports.fileChangesForImport=L;exports.filesForImportMode=j;exports.formatWarningLine=b;exports.hasNativeImportMode=v;exports.projectForImportMode=I;exports.resolveImportMode=F;
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./upload-CGxfSSDN.cjs"),g=require("./import-mode-YW6Lr4SU.cjs"),I={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",pdf:"application/pdf",eps:"application/postscript",ps:"application/postscript",bmp:"image/bmp",tiff:"image/tiff",tif:"image/tiff",webp:"image/webp",ico:"image/vnd.microsoft.icon"};function b(t){const o=t.split(".").pop()?.toLowerCase()??"";return I[o]??"application/octet-stream"}const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function A(t){const o=t.length,s=[];for(let n=0;n<o;n+=3){const r=t[n],l=n+1<o,a=n+2<o,u=l?t[n+1]:0,c=a?t[n+2]:0;s.push(h[r>>2]),s.push(h[(r&3)<<4|u>>4]),s.push(l?h[(u&15)<<2|c>>6]:"="),s.push(a?h[c&63]:"=")}return s.join("")}function M(t){return{ref:t.ref,kind:"file",title:t.fileName,short_description:t.fileName,file:{filename:t.fileName,content_type:b(t.fileName),data:A(t.data)}}}function _(t){return{title:t.title,docinfo:t.docinfo,document_type:t.documentKind,divisions_attributes:t.divisions.map(o=>({ref:o.xmlId,source:o.content,source_format:o.sourceFormat,is_root:o.isRoot})),assets_attributes:t.assets.map(M)}}const v={mainSourcePath:"source/main.ptx",publicationPath:"publication/publication.ptx",projectFilePath:"project.ptx",docinfoPath:"source/docinfo.ptx"};function T(t){return e.findAnyElement(t,"pretext")?t:`<pretext>
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./upload-BtS22hIH.cjs"),f=require("./import-mode-DuPFMu97.cjs"),F={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",pdf:"application/pdf",eps:"application/postscript",ps:"application/postscript",bmp:"image/bmp",tiff:"image/tiff",tif:"image/tiff",webp:"image/webp",ico:"image/vnd.microsoft.icon"};function M(t){const o=t.split(".").pop()?.toLowerCase()??"";return F[o]??"application/octet-stream"}const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function _(t){const o=t.length,s=[];for(let n=0;n<o;n+=3){const r=t[n],l=n+1<o,a=n+2<o,u=l?t[n+1]:0,c=a?t[n+2]:0;s.push(h[r>>2]),s.push(h[(r&3)<<4|u>>4]),s.push(l?h[(u&15)<<2|c>>6]:"="),s.push(a?h[c&63]:"=")}return s.join("")}function b(t){return{ref:t.ref,kind:"file",title:t.fileName,short_description:t.fileName,file:{filename:t.fileName,content_type:M(t.fileName),data:_(t.data)}}}function A(t){return{title:t.title,docinfo:t.docinfo,document_type:t.documentKind,divisions_attributes:t.divisions.map(o=>({ref:o.xmlId,source:o.content,source_format:o.sourceFormat,is_root:o.isRoot})),assets_attributes:t.assets.map(b)}}const v={mainSourcePath:"source/main.ptx",publicationPath:"publication/publication.ptx",projectFilePath:"project.ptx",docinfoPath:"source/docinfo.ptx"};function T(t){return e.findAnyElement(t,"pretext")?t:`<pretext>
2
2
  ${t}
3
- </pretext>`}function L(t,o,s){const n=new Map,r=[],l=`${o}-`;return t.forEach((a,u)=>{const c=a.attributes["xml:id"];let p;if(c){const m=e.slugify(c);p=m.startsWith(l)?m:`${l}${m}`}else p=`${l}${e.padIndex(u+1,t.length)}`,s.push({action:"anomaly",severity:"info",kind:"structure",category:"missing_xml_id",macro:a.name,occurrences:1,message:`<${a.name}> at position ${u+1} has no xml:id; using \`${p}\` as filename.`});const d=n.get(p)??0;n.set(p,d+1);const i=d===0?p:`${p}-${d+1}`;r.push({span:a,slug:i,filename:`${i}.ptx`})}),r}function C(t,o,s,n){const r=e.findTopLevelElements(t,"section");if(r.length===0)return t;const a=L(r,"sec",n).map(u=>{const c=`source/${o}/${u.filename}`;return s[c]=e.withProlog(u.span.outer),{start:u.span.start,end:u.span.end,replacement:`<xi:include href="${o}/${u.filename}"/>`}});return e.spliceReplacements(t,a)}function R(t,o,s){const n=e.findAnyElement(t,"book");if(!n)return s.push({action:"anomaly",severity:"warning",kind:"structure",category:"missing_root",macro:"book",occurrences:1,message:"Document was treated as a book but no <book> element found; emitting as a single file."}),S(t,o);const r={},l=e.findTopLevelElements(n.inner,"chapter");let a=n.inner;if(o.splitChapters&&l.length>0){const d=L(l,"ch",s).map(i=>{let m=i.span.outer;if(o.splitSections){const f=i.span.inner,P=C(f,i.slug,r,s);m=i.span.outer.slice(0,i.span.startTagEnd-i.span.start)+P+i.span.outer.slice(i.span.contentEnd-i.span.start)}const x=`source/${i.filename}`;return r[x]=e.withProlog(m),{start:i.span.start,end:i.span.end,replacement:`<xi:include href="${i.filename}"/>`}});a=e.spliceReplacements(n.inner,d)}const u=t.slice(n.start,n.startTagEnd)+a+t.slice(n.contentEnd,n.end),c=t.slice(0,n.start)+u+t.slice(n.end);return r[o.mainSourcePath]=e.withProlog(e.ensureXIncludeNamespace(T(c.trim()))),r}function S(t,o,s){const n={};return n[o.mainSourcePath]=e.withProlog(T(t.trim())),n}function y(t,o={}){const s=[],n=o.documentKind??e.detectDocumentKind(t),r={splitChapters:o.splitChapters??n==="book",splitSections:o.splitSections??!1,mainSourcePath:o.mainSourcePath??v.mainSourcePath,publicationPath:o.publicationPath??v.publicationPath,projectFilePath:o.projectFilePath??v.projectFilePath,docinfoPath:o.docinfoPath??v.docinfoPath},l=n==="book"?R(t,r,s):S(t,r);return l[r.projectFilePath]=e.renderProjectPtx({mainSource:r.mainSourcePath,publication:r.publicationPath}),l[r.publicationPath]=e.renderPublicationPtx(),{files:l,documentKind:n,warnings:s}}class E extends Error{constructor(){super("Import cancelled."),this.name="ConversionCancelledError"}}let j=0;function F(t,o,s={}){const n=`convert-${j++}`,r=t(),{assets:l={},...a}=s;let u;const c=new Promise((d,i)=>{let m=!1;const x=f=>{m||(m=!0,r.terminate(),f())};u=()=>x(()=>i(new E)),r.addEventListener("message",f=>{const P=f.data;if(!(!P||P.requestId!==n)){if(P.type==="result"){x(()=>d(P.result));return}x(()=>i(new Error(P.message)))}}),r.addEventListener("error",f=>{const P=typeof f=="object"&&f&&"message"in f?String(f.message):"The import worker failed to start.";x(()=>i(new Error(P)))})}),p=[...new Set(Object.values(l).map(d=>d.buffer).filter(d=>d instanceof ArrayBuffer))];return r.postMessage({type:"convert",requestId:n,files:o,assets:l,options:a},p),{result:c,cancel:()=>u?.()}}function k(t){const{createWorker:o,id:s="worker",label:n="Built-in converter",description:r="Create a new project starting with LaTeX, Markdown, or PreTeXt files.",acceptExtensions:l}=t;let a=null;const u=async(c,p)=>{a?.cancel(),a=F(o,c,p);try{return await a.result}finally{a=null}};return{id:s,label:n,description:r,acceptExtensions:l,prepare:async c=>{const{files:p,assets:d}=await e.extractUpload(c);return{fileName:c.name,files:p,assets:d,analysis:e.analyzeImportSources(p)}},convertPrepared:(c,p)=>u(c.files,{...p,assets:c.assets}),convertFile:async(c,p)=>{const{files:d,assets:i}=await e.extractUpload(c);return u(d,{...p,assets:i})},cancel:()=>{a?.cancel(),a=null}}}exports.CLEAN_RULES=e.CLEAN_RULES;exports.LATEX_DIVISION_COMMANDS=e.LATEX_DIVISION_COMMANDS;exports.LATEX_FORMAT_MARKERS=e.LATEX_FORMAT_MARKERS;exports.MARKDOWN_FORMAT_MARKERS=e.MARKDOWN_FORMAT_MARKERS;exports.MAX_SUGGESTED_SPLIT_LEVEL=e.MAX_SUGGESTED_SPLIT_LEVEL;exports.PRETEXT_DIVISION_TAGS=e.PRETEXT_DIVISION_TAGS;exports.PRETEXT_ROOT_TAGS=e.PRETEXT_ROOT_TAGS;exports.analyzeImportSources=e.analyzeImportSources;exports.applyLatexFixes=e.applyLatexFixes;exports.attachLatexRoots=e.attachLatexRoots;exports.attachMarkdownRoots=e.attachMarkdownRoots;exports.buildDivisionPool=e.buildDivisionPool;exports.buildNativeDivisionPool=e.buildNativeDivisionPool;exports.carryOverProjectFiles=e.carryOverProjectFiles;exports.cleanLatex=e.cleanLatex;exports.cleanLatexInChunks=e.cleanLatexInChunks;exports.cleanLatexText=e.cleanLatexText;exports.convertLatexToPretext=e.convertLatexToPretext;exports.convertMarkdownToPretext=e.convertMarkdownToPretext;exports.convertSourceToPretext=e.convertSourceToPretext;exports.defaultAttachLevel=e.defaultAttachLevel;exports.defaultManifestTarget=e.defaultManifestTarget;exports.detectDocumentKind=e.detectDocumentKind;exports.detectSourceFormat=e.detectSourceFormat;exports.divisionChildRefs=e.divisionChildRefs;exports.divisionsAtLevel=e.divisionsAtLevel;exports.expandPretextIncludes=e.expandPretextIncludes;exports.extractUpload=e.extractUpload;exports.filePrefixForDivision=e.filePrefixForDivision;exports.findLatexFixes=e.findLatexFixes;exports.findLatexHeaders=e.findLatexHeaders;exports.findProjectManifest=e.findProjectManifest;exports.fixesToWarnings=e.fixesToWarnings;exports.getConversionErrorMessage=e.getConversionErrorMessage;exports.getLatexCleanDiagnostics=e.getLatexCleanDiagnostics;exports.handleImportUploadFile=e.handleImportUploadFile;exports.importProjectFromFiles=e.importProjectFromFiles;exports.isDivisionTag=e.isDivisionTag;exports.latexDivisionHierarchy=e.latexDivisionHierarchy;exports.latexFixesToCodeActions=e.latexFixesToCodeActions;exports.mergeChunksAtLevel=e.mergeChunksAtLevel;exports.normalizePretextSource=e.normalizePretextSource;exports.parseLatexDivisions=e.parseLatexDivisions;exports.parseProjectManifest=e.parseProjectManifest;exports.relayoutImport=e.relayoutImport;exports.renderProjectPtx=e.renderProjectPtx;exports.renderProjectPtxFromManifest=e.renderProjectPtxFromManifest;exports.renderPublicationPtx=e.renderPublicationPtx;exports.resolveImportSplitLevel=e.resolveImportSplitLevel;exports.resolveSplitLevel=e.resolveSplitLevel;exports.sanitizeRef=e.sanitizeRef;exports.serializeProjectToFiles=e.serializeProjectToFiles;exports.suggestSplitLevel=e.suggestSplitLevel;exports.assetsForImportMode=g.assetsForImportMode;exports.diffHunks=g.diffHunks;exports.diffLines=g.diffLines;exports.diffStats=g.diffStats;exports.fileChangesForImport=g.fileChangesForImport;exports.filesForImportMode=g.filesForImportMode;exports.formatWarningLine=g.formatWarningLine;exports.projectForImportMode=g.projectForImportMode;exports.ConversionCancelledError=E;exports.buildPretextProjectFiles=y;exports.createWorkerEngine=k;exports.runConversionInWorker=F;exports.serializeProjectToPlusPayload=_;
3
+ </pretext>`}function E(t,o,s){const n=new Map,r=[],l=`${o}-`;return t.forEach((a,u)=>{const c=a.attributes["xml:id"];let p;if(c){const P=e.slugify(c);p=P.startsWith(l)?P:`${l}${P}`}else p=`${l}${e.padIndex(u+1,t.length)}`,s.push({action:"anomaly",severity:"info",kind:"structure",category:"missing_xml_id",macro:a.name,occurrences:1,message:`<${a.name}> at position ${u+1} has no xml:id; using \`${p}\` as filename.`});const d=n.get(p)??0;n.set(p,d+1);const i=d===0?p:`${p}-${d+1}`;r.push({span:a,slug:i,filename:`${i}.ptx`})}),r}function C(t,o,s,n){const r=e.findTopLevelElements(t,"section");if(r.length===0)return t;const a=E(r,"sec",n).map(u=>{const c=`source/${o}/${u.filename}`;return s[c]=e.withProlog(u.span.outer),{start:u.span.start,end:u.span.end,replacement:`<xi:include href="${o}/${u.filename}"/>`}});return e.spliceReplacements(t,a)}function R(t,o,s){const n=e.findAnyElement(t,"book");if(!n)return s.push({action:"anomaly",severity:"warning",kind:"structure",category:"missing_root",macro:"book",occurrences:1,message:"Document was treated as a book but no <book> element found; emitting as a single file."}),L(t,o);const r={},l=e.findTopLevelElements(n.inner,"chapter");let a=n.inner;if(o.splitChapters&&l.length>0){const d=E(l,"ch",s).map(i=>{let P=i.span.outer;if(o.splitSections){const m=i.span.inner,g=C(m,i.slug,r,s);P=i.span.outer.slice(0,i.span.startTagEnd-i.span.start)+g+i.span.outer.slice(i.span.contentEnd-i.span.start)}const x=`source/${i.filename}`;return r[x]=e.withProlog(P),{start:i.span.start,end:i.span.end,replacement:`<xi:include href="${i.filename}"/>`}});a=e.spliceReplacements(n.inner,d)}const u=t.slice(n.start,n.startTagEnd)+a+t.slice(n.contentEnd,n.end),c=t.slice(0,n.start)+u+t.slice(n.end);return r[o.mainSourcePath]=e.withProlog(e.ensureXIncludeNamespace(T(c.trim()))),r}function L(t,o,s){const n={};return n[o.mainSourcePath]=e.withProlog(T(t.trim())),n}function y(t,o={}){const s=[],n=o.documentKind??e.detectDocumentKind(t),r={splitChapters:o.splitChapters??n==="book",splitSections:o.splitSections??!1,mainSourcePath:o.mainSourcePath??v.mainSourcePath,publicationPath:o.publicationPath??v.publicationPath,projectFilePath:o.projectFilePath??v.projectFilePath,docinfoPath:o.docinfoPath??v.docinfoPath},l=n==="book"?R(t,r,s):L(t,r);return l[r.projectFilePath]=e.renderProjectPtx({mainSource:r.mainSourcePath,publication:r.publicationPath}),l[r.publicationPath]=e.renderPublicationPtx(),{files:l,documentKind:n,warnings:s}}class S extends Error{constructor(){super("Import cancelled."),this.name="ConversionCancelledError"}}let D=0;function I(t,o,s={}){const n=`convert-${D++}`,r=t(),{assets:l={},...a}=s;let u;const c=new Promise((d,i)=>{let P=!1;const x=m=>{P||(P=!0,r.terminate(),m())};u=()=>x(()=>i(new S)),r.addEventListener("message",m=>{const g=m.data;if(!(!g||g.requestId!==n)){if(g.type==="result"){x(()=>d(g.result));return}x(()=>i(new Error(g.message)))}}),r.addEventListener("error",m=>{const g=typeof m=="object"&&m&&"message"in m?String(m.message):"The import worker failed to start.";x(()=>i(new Error(g)))})}),p=[...new Set(Object.values(l).map(d=>d.buffer).filter(d=>d instanceof ArrayBuffer))];return r.postMessage({type:"convert",requestId:n,files:o,assets:l,options:a},p),{result:c,cancel:()=>u?.()}}function j(t){const{createWorker:o,id:s="worker",label:n="Built-in converter",description:r="Create a new project starting with LaTeX, Markdown, or PreTeXt files.",acceptExtensions:l}=t;let a=null;const u=async(c,p)=>{a?.cancel(),a=I(o,c,p);try{return await a.result}finally{a=null}};return{id:s,label:n,description:r,acceptExtensions:l,prepare:async c=>{const{files:p,assets:d}=await e.extractUpload(c);return{fileName:c.name,files:p,assets:d,analysis:e.analyzeImportSources(p)}},convertPrepared:(c,p)=>u(c.files,{...p,assets:c.assets}),convertFile:async(c,p)=>{const{files:d,assets:i}=await e.extractUpload(c);return u(d,{...p,assets:i})},cancel:()=>{a?.cancel(),a=null}}}exports.CLEAN_RULES=e.CLEAN_RULES;exports.LATEX_DIVISION_COMMANDS=e.LATEX_DIVISION_COMMANDS;exports.LATEX_FORMAT_MARKERS=e.LATEX_FORMAT_MARKERS;exports.MARKDOWN_FORMAT_MARKERS=e.MARKDOWN_FORMAT_MARKERS;exports.MAX_SUGGESTED_SPLIT_LEVEL=e.MAX_SUGGESTED_SPLIT_LEVEL;exports.PRETEXT_DIVISION_TAGS=e.PRETEXT_DIVISION_TAGS;exports.PRETEXT_ROOT_TAGS=e.PRETEXT_ROOT_TAGS;exports.analyzeImportSources=e.analyzeImportSources;exports.applyLatexFixes=e.applyLatexFixes;exports.attachLatexRoots=e.attachLatexRoots;exports.attachMarkdownRoots=e.attachMarkdownRoots;exports.buildDivisionPool=e.buildDivisionPool;exports.buildNativeDivisionPool=e.buildNativeDivisionPool;exports.carryOverProjectFiles=e.carryOverProjectFiles;exports.cleanLatex=e.cleanLatex;exports.cleanLatexInChunks=e.cleanLatexInChunks;exports.cleanLatexText=e.cleanLatexText;exports.convertLatexToPretext=e.convertLatexToPretext;exports.convertMarkdownToPretext=e.convertMarkdownToPretext;exports.convertSourceToPretext=e.convertSourceToPretext;exports.defaultAttachLevel=e.defaultAttachLevel;exports.defaultManifestTarget=e.defaultManifestTarget;exports.detectDocumentKind=e.detectDocumentKind;exports.detectSourceFormat=e.detectSourceFormat;exports.divisionChildRefs=e.divisionChildRefs;exports.divisionsAtLevel=e.divisionsAtLevel;exports.expandPretextIncludes=e.expandPretextIncludes;exports.extractUpload=e.extractUpload;exports.filePrefixForDivision=e.filePrefixForDivision;exports.findLatexFixes=e.findLatexFixes;exports.findLatexHeaders=e.findLatexHeaders;exports.findProjectManifest=e.findProjectManifest;exports.fixesToWarnings=e.fixesToWarnings;exports.getConversionErrorMessage=e.getConversionErrorMessage;exports.getLatexCleanDiagnostics=e.getLatexCleanDiagnostics;exports.handleImportUploadFile=e.handleImportUploadFile;exports.importProjectFromFiles=e.importProjectFromFiles;exports.isDivisionTag=e.isDivisionTag;exports.latexDivisionHierarchy=e.latexDivisionHierarchy;exports.latexFixesToCodeActions=e.latexFixesToCodeActions;exports.mergeChunksAtLevel=e.mergeChunksAtLevel;exports.normalizePretextSource=e.normalizePretextSource;exports.parseLatexDivisions=e.parseLatexDivisions;exports.parseProjectManifest=e.parseProjectManifest;exports.relayoutImport=e.relayoutImport;exports.renderProjectPtx=e.renderProjectPtx;exports.renderProjectPtxFromManifest=e.renderProjectPtxFromManifest;exports.renderPublicationPtx=e.renderPublicationPtx;exports.resolveImportSplitLevel=e.resolveImportSplitLevel;exports.resolveSplitLevel=e.resolveSplitLevel;exports.sanitizeRef=e.sanitizeRef;exports.serializeProjectToFiles=e.serializeProjectToFiles;exports.suggestSplitLevel=e.suggestSplitLevel;exports.DEFAULT_IMPORT_MODE=f.DEFAULT_IMPORT_MODE;exports.assetsForImportMode=f.assetsForImportMode;exports.diffHunks=f.diffHunks;exports.diffLines=f.diffLines;exports.diffStats=f.diffStats;exports.fileChangesForImport=f.fileChangesForImport;exports.filesForImportMode=f.filesForImportMode;exports.formatWarningLine=f.formatWarningLine;exports.hasNativeImportMode=f.hasNativeImportMode;exports.projectForImportMode=f.projectForImportMode;exports.resolveImportMode=f.resolveImportMode;exports.ConversionCancelledError=S;exports.buildPretextProjectFiles=y;exports.createWorkerEngine=j;exports.runConversionInWorker=I;exports.serializeProjectToPlusPayload=A;
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export { attachLatexRoots, attachMarkdownRoots, defaultAttachLevel, type AttachL
11
11
  export { defaultManifestTarget, findProjectManifest, parseProjectManifest, type ManifestTarget, type ProjectManifest, } from './lib/project/manifest';
12
12
  export { carryOverProjectFiles, renderProjectPtxFromManifest, type CarryOverOptions, type CarryOverResult, } from './lib/project/existing-project';
13
13
  export { PRETEXT_DIVISION_TAGS, PRETEXT_ROOT_TAGS, filePrefixForDivision, isDivisionTag, type PretextDivisionTag, type PretextRootTag, } from './lib/pretext-divisions';
14
- export { filesForImportMode, assetsForImportMode, projectForImportMode, formatWarningLine, type ImportMode, } from './lib/import-mode';
14
+ export { DEFAULT_IMPORT_MODE, filesForImportMode, assetsForImportMode, hasNativeImportMode, projectForImportMode, resolveImportMode, formatWarningLine, type ImportMode, } from './lib/import-mode';
15
15
  export { cleanLatex, fixesToWarnings } from './lib/clean/clean-latex';
16
16
  export type { CleanLatexOptions, CleanLatexResult, } from './lib/clean/clean-latex';
17
17
  export { CLEAN_RULES, findLatexFixes, applyLatexFixes, cleanLatexText, getLatexCleanDiagnostics, latexFixesToCodeActions, } from '@pretextbook/latex-style-pretext';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { d as w, r as I, a as _, f as E, b as T, w as x, s as v, e as C, c as k, p as y, g as b, h as A } from "./upload-BBHV4rXJ.js";
2
- import { C as q, L as V, i as Y, M as J, j as Q, P as Z, k as ee, l as te, m as se, n as ne, o as ae, q as oe, t as re, u as ie, v as ce, x as le, y as ue, z as pe, A as fe, B as me, D as de, E as ge, F as Pe, G as he, H as xe, I as be, J as Ee, K as Te, N as ve, O as Se, Q as Le, R as Fe, S as we, T as Ie, U as _e, V as Ce, W as ke, X as ye, Y as Ae, Z as Me, _ as je, $ as Re, a0 as $e, a1 as De, a2 as Ne, a3 as Oe, a4 as Be, a5 as We } from "./upload-BBHV4rXJ.js";
3
- import { a as Ke, d as ze, b as Ue, c as Ge, f as He, e as qe, g as Ve, p as Ye } from "./import-mode-GqdypBfV.js";
1
+ import { d as I, r as _, a as w, f as T, b, w as x, s as v, e as C, c as k, p as y, g as E, h as A } from "./upload-BmErkg8I.js";
2
+ import { C as q, L as V, i as Y, M as J, j as Q, P as Z, k as ee, l as te, m as se, n as ae, o as ne, q as oe, t as re, u as ie, v as ce, x as le, y as ue, z as pe, A as fe, B as me, D as de, E as ge, F as Pe, G as he, H as xe, I as Ee, J as Te, K as be, N as ve, O as Se, Q as Le, R as Fe, S as Ie, T as _e, U as we, V as Ce, W as ke, X as ye, Y as Ae, Z as Me, _ as Re, $ as je, a0 as De, a1 as $e, a2 as Ne, a3 as Oe, a4 as Be, a5 as We } from "./upload-BmErkg8I.js";
3
+ import { D as Ke, a as ze, d as Ue, b as Ge, c as He, f as qe, e as Ve, g as Ye, h as Je, p as Qe, r as Ze } from "./import-mode-BaaBvzcy.js";
4
4
  const M = {
5
5
  png: "image/png",
6
6
  jpg: "image/jpeg",
@@ -15,20 +15,20 @@ const M = {
15
15
  webp: "image/webp",
16
16
  ico: "image/vnd.microsoft.icon"
17
17
  };
18
- function j(e) {
18
+ function R(e) {
19
19
  const s = e.split(".").pop()?.toLowerCase() ?? "";
20
20
  return M[s] ?? "application/octet-stream";
21
21
  }
22
22
  const P = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
23
- function R(e) {
23
+ function j(e) {
24
24
  const s = e.length, o = [];
25
25
  for (let t = 0; t < s; t += 3) {
26
- const n = e[t], c = t + 1 < s, r = t + 2 < s, l = c ? e[t + 1] : 0, i = r ? e[t + 2] : 0;
27
- o.push(P[n >> 2]), o.push(P[(n & 3) << 4 | l >> 4]), o.push(c ? P[(l & 15) << 2 | i >> 6] : "="), o.push(r ? P[i & 63] : "=");
26
+ const a = e[t], c = t + 1 < s, r = t + 2 < s, l = c ? e[t + 1] : 0, i = r ? e[t + 2] : 0;
27
+ o.push(P[a >> 2]), o.push(P[(a & 3) << 4 | l >> 4]), o.push(c ? P[(l & 15) << 2 | i >> 6] : "="), o.push(r ? P[i & 63] : "=");
28
28
  }
29
29
  return o.join("");
30
30
  }
31
- function $(e) {
31
+ function D(e) {
32
32
  return {
33
33
  ref: e.ref,
34
34
  kind: "file",
@@ -36,8 +36,8 @@ function $(e) {
36
36
  short_description: e.fileName,
37
37
  file: {
38
38
  filename: e.fileName,
39
- content_type: j(e.fileName),
40
- data: R(e.data)
39
+ content_type: R(e.fileName),
40
+ data: j(e.data)
41
41
  }
42
42
  };
43
43
  }
@@ -52,7 +52,7 @@ function K(e) {
52
52
  source_format: s.sourceFormat,
53
53
  is_root: s.isRoot
54
54
  })),
55
- assets_attributes: e.assets.map($)
55
+ assets_attributes: e.assets.map(D)
56
56
  };
57
57
  }
58
58
  const h = {
@@ -62,12 +62,12 @@ const h = {
62
62
  docinfoPath: "source/docinfo.ptx"
63
63
  };
64
64
  function S(e) {
65
- return E(e, "pretext") ? e : `<pretext>
65
+ return T(e, "pretext") ? e : `<pretext>
66
66
  ${e}
67
67
  </pretext>`;
68
68
  }
69
69
  function L(e, s, o) {
70
- const t = /* @__PURE__ */ new Map(), n = [], c = `${s}-`;
70
+ const t = /* @__PURE__ */ new Map(), a = [], c = `${s}-`;
71
71
  return e.forEach((r, l) => {
72
72
  const i = r.attributes["xml:id"];
73
73
  let u;
@@ -86,19 +86,19 @@ function L(e, s, o) {
86
86
  });
87
87
  const p = t.get(u) ?? 0;
88
88
  t.set(u, p + 1);
89
- const a = p === 0 ? u : `${u}-${p + 1}`;
90
- n.push({
89
+ const n = p === 0 ? u : `${u}-${p + 1}`;
90
+ a.push({
91
91
  span: r,
92
- slug: a,
93
- filename: `${a}.ptx`
92
+ slug: n,
93
+ filename: `${n}.ptx`
94
94
  });
95
- }), n;
95
+ }), a;
96
96
  }
97
- function D(e, s, o, t) {
98
- const n = T(e, "section");
99
- if (n.length === 0)
97
+ function $(e, s, o, t) {
98
+ const a = b(e, "section");
99
+ if (a.length === 0)
100
100
  return e;
101
- const r = L(n, "sec", t).map((l) => {
101
+ const r = L(a, "sec", t).map((l) => {
102
102
  const i = `source/${s}/${l.filename}`;
103
103
  return o[i] = x(l.span.outer), {
104
104
  start: l.span.start,
@@ -109,7 +109,7 @@ function D(e, s, o, t) {
109
109
  return v(e, r);
110
110
  }
111
111
  function N(e, s, o) {
112
- const t = E(e, "book");
112
+ const t = T(e, "book");
113
113
  if (!t)
114
114
  return o.push({
115
115
  action: "anomaly",
@@ -120,33 +120,33 @@ function N(e, s, o) {
120
120
  occurrences: 1,
121
121
  message: "Document was treated as a book but no <book> element found; emitting as a single file."
122
122
  }), F(e, s);
123
- const n = {}, c = T(t.inner, "chapter");
123
+ const a = {}, c = b(t.inner, "chapter");
124
124
  let r = t.inner;
125
125
  if (s.splitChapters && c.length > 0) {
126
- const p = L(c, "ch", o).map((a) => {
127
- let m = a.span.outer;
126
+ const p = L(c, "ch", o).map((n) => {
127
+ let m = n.span.outer;
128
128
  if (s.splitSections) {
129
- const f = a.span.inner, d = D(
129
+ const f = n.span.inner, d = $(
130
130
  f,
131
- a.slug,
132
- n,
131
+ n.slug,
132
+ a,
133
133
  o
134
134
  );
135
- m = a.span.outer.slice(0, a.span.startTagEnd - a.span.start) + d + a.span.outer.slice(a.span.contentEnd - a.span.start);
135
+ m = n.span.outer.slice(0, n.span.startTagEnd - n.span.start) + d + n.span.outer.slice(n.span.contentEnd - n.span.start);
136
136
  }
137
- const g = `source/${a.filename}`;
138
- return n[g] = x(m), {
139
- start: a.span.start,
140
- end: a.span.end,
141
- replacement: `<xi:include href="${a.filename}"/>`
137
+ const g = `source/${n.filename}`;
138
+ return a[g] = x(m), {
139
+ start: n.span.start,
140
+ end: n.span.end,
141
+ replacement: `<xi:include href="${n.filename}"/>`
142
142
  };
143
143
  });
144
144
  r = v(t.inner, p);
145
145
  }
146
146
  const l = e.slice(t.start, t.startTagEnd) + r + e.slice(t.contentEnd, t.end), i = e.slice(0, t.start) + l + e.slice(t.end);
147
- return n[s.mainSourcePath] = x(
147
+ return a[s.mainSourcePath] = x(
148
148
  C(S(i.trim()))
149
- ), n;
149
+ ), a;
150
150
  }
151
151
  function F(e, s, o) {
152
152
  const t = {};
@@ -155,18 +155,18 @@ function F(e, s, o) {
155
155
  ), t;
156
156
  }
157
157
  function z(e, s = {}) {
158
- const o = [], t = s.documentKind ?? w(e), n = {
158
+ const o = [], t = s.documentKind ?? I(e), a = {
159
159
  splitChapters: s.splitChapters ?? t === "book",
160
160
  splitSections: s.splitSections ?? !1,
161
161
  mainSourcePath: s.mainSourcePath ?? h.mainSourcePath,
162
162
  publicationPath: s.publicationPath ?? h.publicationPath,
163
163
  projectFilePath: s.projectFilePath ?? h.projectFilePath,
164
164
  docinfoPath: s.docinfoPath ?? h.docinfoPath
165
- }, c = t === "book" ? N(e, n, o) : F(e, n);
166
- return c[n.projectFilePath] = I({
167
- mainSource: n.mainSourcePath,
168
- publication: n.publicationPath
169
- }), c[n.publicationPath] = _(), { files: c, documentKind: t, warnings: o };
165
+ }, c = t === "book" ? N(e, a, o) : F(e, a);
166
+ return c[a.projectFilePath] = _({
167
+ mainSource: a.mainSourcePath,
168
+ publication: a.publicationPath
169
+ }), c[a.publicationPath] = w(), { files: c, documentKind: t, warnings: o };
170
170
  }
171
171
  class O extends Error {
172
172
  constructor() {
@@ -175,25 +175,25 @@ class O extends Error {
175
175
  }
176
176
  let B = 0;
177
177
  function W(e, s, o = {}) {
178
- const t = `convert-${B++}`, n = e(), { assets: c = {}, ...r } = o;
178
+ const t = `convert-${B++}`, a = e(), { assets: c = {}, ...r } = o;
179
179
  let l;
180
- const i = new Promise((p, a) => {
180
+ const i = new Promise((p, n) => {
181
181
  let m = !1;
182
182
  const g = (f) => {
183
- m || (m = !0, n.terminate(), f());
183
+ m || (m = !0, a.terminate(), f());
184
184
  };
185
- l = () => g(() => a(new O())), n.addEventListener("message", (f) => {
185
+ l = () => g(() => n(new O())), a.addEventListener("message", (f) => {
186
186
  const d = f.data;
187
187
  if (!(!d || d.requestId !== t)) {
188
188
  if (d.type === "result") {
189
189
  g(() => p(d.result));
190
190
  return;
191
191
  }
192
- g(() => a(new Error(d.message)));
192
+ g(() => n(new Error(d.message)));
193
193
  }
194
- }), n.addEventListener("error", (f) => {
194
+ }), a.addEventListener("error", (f) => {
195
195
  const d = typeof f == "object" && f && "message" in f ? String(f.message) : "The import worker failed to start.";
196
- g(() => a(new Error(d)));
196
+ g(() => n(new Error(d)));
197
197
  });
198
198
  }), u = [
199
199
  ...new Set(
@@ -202,7 +202,7 @@ function W(e, s, o = {}) {
202
202
  )
203
203
  )
204
204
  ];
205
- return n.postMessage(
205
+ return a.postMessage(
206
206
  { type: "convert", requestId: t, files: s, assets: c, options: r },
207
207
  u
208
208
  ), { result: i, cancel: () => l?.() };
@@ -212,7 +212,7 @@ function U(e) {
212
212
  createWorker: s,
213
213
  id: o = "worker",
214
214
  label: t = "Built-in converter",
215
- description: n = "Create a new project starting with LaTeX, Markdown, or PreTeXt files.",
215
+ description: a = "Create a new project starting with LaTeX, Markdown, or PreTeXt files.",
216
216
  acceptExtensions: c
217
217
  } = e;
218
218
  let r = null;
@@ -227,10 +227,10 @@ function U(e) {
227
227
  return {
228
228
  id: o,
229
229
  label: t,
230
- description: n,
230
+ description: a,
231
231
  acceptExtensions: c,
232
232
  prepare: async (i) => {
233
- const { files: u, assets: p } = await b(i);
233
+ const { files: u, assets: p } = await E(i);
234
234
  return {
235
235
  fileName: i.name,
236
236
  files: u,
@@ -240,8 +240,8 @@ function U(e) {
240
240
  },
241
241
  convertPrepared: (i, u) => l(i.files, { ...u, assets: i.assets }),
242
242
  convertFile: async (i, u) => {
243
- const { files: p, assets: a } = await b(i);
244
- return l(p, { ...u, assets: a });
243
+ const { files: p, assets: n } = await E(i);
244
+ return l(p, { ...u, assets: n });
245
245
  },
246
246
  cancel: () => {
247
247
  r?.cancel(), r = null;
@@ -251,6 +251,7 @@ function U(e) {
251
251
  export {
252
252
  q as CLEAN_RULES,
253
253
  O as ConversionCancelledError,
254
+ Ke as DEFAULT_IMPORT_MODE,
254
255
  V as LATEX_DIVISION_COMMANDS,
255
256
  Y as LATEX_FORMAT_MARKERS,
256
257
  J as MARKDOWN_FORMAT_MARKERS,
@@ -259,10 +260,10 @@ export {
259
260
  ee as PRETEXT_ROOT_TAGS,
260
261
  A as analyzeImportSources,
261
262
  te as applyLatexFixes,
262
- Ke as assetsForImportMode,
263
+ ze as assetsForImportMode,
263
264
  se as attachLatexRoots,
264
- ne as attachMarkdownRoots,
265
- ae as buildDivisionPool,
265
+ ae as attachMarkdownRoots,
266
+ ne as buildDivisionPool,
266
267
  oe as buildNativeDivisionPool,
267
268
  z as buildPretextProjectFiles,
268
269
  re as carryOverProjectFiles,
@@ -275,40 +276,42 @@ export {
275
276
  U as createWorkerEngine,
276
277
  me as defaultAttachLevel,
277
278
  de as defaultManifestTarget,
278
- w as detectDocumentKind,
279
+ I as detectDocumentKind,
279
280
  ge as detectSourceFormat,
280
- ze as diffHunks,
281
- Ue as diffLines,
282
- Ge as diffStats,
281
+ Ue as diffHunks,
282
+ Ge as diffLines,
283
+ He as diffStats,
283
284
  Pe as divisionChildRefs,
284
285
  he as divisionsAtLevel,
285
286
  xe as expandPretextIncludes,
286
- b as extractUpload,
287
- He as fileChangesForImport,
288
- be as filePrefixForDivision,
289
- qe as filesForImportMode,
290
- Ee as findLatexFixes,
291
- Te as findLatexHeaders,
287
+ E as extractUpload,
288
+ qe as fileChangesForImport,
289
+ Ee as filePrefixForDivision,
290
+ Ve as filesForImportMode,
291
+ Te as findLatexFixes,
292
+ be as findLatexHeaders,
292
293
  ve as findProjectManifest,
293
294
  Se as fixesToWarnings,
294
- Ve as formatWarningLine,
295
+ Ye as formatWarningLine,
295
296
  Le as getConversionErrorMessage,
296
297
  Fe as getLatexCleanDiagnostics,
297
- we as handleImportUploadFile,
298
- Ie as importProjectFromFiles,
299
- _e as isDivisionTag,
298
+ Ie as handleImportUploadFile,
299
+ Je as hasNativeImportMode,
300
+ _e as importProjectFromFiles,
301
+ we as isDivisionTag,
300
302
  Ce as latexDivisionHierarchy,
301
303
  ke as latexFixesToCodeActions,
302
304
  ye as mergeChunksAtLevel,
303
305
  Ae as normalizePretextSource,
304
306
  Me as parseLatexDivisions,
305
- je as parseProjectManifest,
306
- Ye as projectForImportMode,
307
- Re as relayoutImport,
308
- I as renderProjectPtx,
309
- $e as renderProjectPtxFromManifest,
310
- _ as renderPublicationPtx,
311
- De as resolveImportSplitLevel,
307
+ Re as parseProjectManifest,
308
+ Qe as projectForImportMode,
309
+ je as relayoutImport,
310
+ _ as renderProjectPtx,
311
+ De as renderProjectPtxFromManifest,
312
+ w as renderPublicationPtx,
313
+ Ze as resolveImportMode,
314
+ $e as resolveImportSplitLevel,
312
315
  Ne as resolveSplitLevel,
313
316
  W as runConversionInWorker,
314
317
  Oe as sanitizeRef,
@@ -1,3 +1,4 @@
1
+ import { CleaningWarning } from './warnings';
1
2
  export interface PreambleInfo {
2
3
  /** Argument of \documentclass{...}, e.g. "book" or "article". Defaults to "article". */
3
4
  documentClass: string;
@@ -5,7 +6,7 @@ export interface PreambleInfo {
5
6
  title: string;
6
7
  /** Inner content of \author{...}, or empty string. */
7
8
  author: string;
8
- /** Collected \newcommand / \renewcommand / \DeclareMathOperator definitions. */
9
+ /** Collected \newcommand / \renewcommand / \DeclareMathOperator / \def definitions. */
9
10
  macros: string;
10
11
  }
11
12
  export declare function splitLatexAtDocument(source: string): {
@@ -18,10 +19,26 @@ export declare function splitLatexAtDocument(source: string): {
18
19
  * Returns the inner content (without surrounding braces), or "".
19
20
  */
20
21
  export declare function extractLatexField(source: string, cmdName: string): string;
22
+ export interface ExtractMacrosResult {
23
+ /** Collected macro definitions, joined with newlines. */
24
+ macros: string;
25
+ /** One warning summarizing any `\def` blocks found (empty if none). */
26
+ warnings: CleaningWarning[];
27
+ }
21
28
  /**
22
29
  * Collects LaTeX macro definition lines from `preamble`, including multi-line
23
30
  * definitions (tracks brace depth to know when a definition is complete).
24
- * Returns the collected definitions joined with newlines.
31
+ *
32
+ * `\def` is kept verbatim alongside `\newcommand` et al. — rewriting its
33
+ * syntax isn't safe in general (delimited parameter text, `\global`/`\edef`
34
+ * semantics, and no way to tell here whether it's redefining an existing
35
+ * command, which would make a mechanical `\newcommand` rewrite fail to
36
+ * build) — but it's reported as a warning, since PreTeXt tooling downstream
37
+ * (e.g. WeBWorK/PG macro extraction) only recognises `\newcommand`.
25
38
  */
26
- export declare function extractMacros(preamble: string): string;
27
- export declare function extractPreambleInfo(preamble: string): PreambleInfo;
39
+ export declare function extractMacros(preamble: string): ExtractMacrosResult;
40
+ export interface ExtractPreambleInfoResult {
41
+ info: PreambleInfo;
42
+ warnings: CleaningWarning[];
43
+ }
44
+ export declare function extractPreambleInfo(preamble: string): ExtractPreambleInfoResult;
@@ -2,6 +2,28 @@ import { CleaningWarning } from './clean/warnings';
2
2
  import { ImportedProject, ImportedProjectSuccess } from './types';
3
3
  /** Which of the result's alternatives the user chose to import. */
4
4
  export type ImportMode = "converted" | "native";
5
+ /**
6
+ * The mode a host gets when it expresses no preference: convert to PreTeXt.
7
+ * Exported so consumers that surface their own default (a VS Code setting, a
8
+ * pretext-plus account preference) can name this one rather than re-spelling
9
+ * the string literal.
10
+ */
11
+ export declare const DEFAULT_IMPORT_MODE: ImportMode;
12
+ /**
13
+ * Does this result actually carry a native alternative? Only LaTeX and
14
+ * Markdown imports produce one — a PreTeXt upload has nothing to keep — so a
15
+ * host or UI that offers the choice should ask this first rather than keying
16
+ * off the detected format.
17
+ */
18
+ export declare function hasNativeImportMode(result: ImportedProjectSuccess): boolean;
19
+ /**
20
+ * The mode that will really be applied to this result, given a preference.
21
+ * A preferred `"native"` collapses to `"converted"` when the result has no
22
+ * native projection, which keeps the mode a host reports (and stores) in step
23
+ * with the files it actually writes — the `*ForImportMode` helpers fall back
24
+ * silently on their own.
25
+ */
26
+ export declare function resolveImportMode(result: ImportedProjectSuccess, preferred?: ImportMode): ImportMode;
5
27
  /**
6
28
  * The division pool the pretext-plus host should serialize for the chosen
7
29
  * mode: the native (LaTeX/Markdown) pool when the user keeps the source