Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
type: no dynamic imports, so the bundle boots on the loader's inline path (#739)
nyblnetfbf1fb5a20e9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex cd75b2e4..52741622 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -35,6 +35,27 @@ concurrency:cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}jobs:+ type-boot-browser:+ runs-on: ubuntu-latest+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 24+ - name: Install browser test runtime+ # Pinned outside app packages: browser automation is not shipped in documents.+ run: |+ npm install --prefix "$RUNNER_TEMP/bento-browser" --no-package-lock --ignore-scripts [email protected]+ "$RUNNER_TEMP/bento-browser/node_modules/.bin/playwright" install --with-deps chromium+ echo "PLAYWRIGHT_MODULE=$RUNNER_TEMP/bento-browser/node_modules/playwright/index.mjs" >> "$GITHUB_ENV"+ - name: Build the tested standalone document+ run: |+ npm ci --prefix type+ npm run build:single --prefix type+ - name: Type boots on the loader's inline path; fields wiring still works+ run: node scripts/test-type-boot-browser.mjs+validate:runs-on: ubuntu-latesttimeout-minutes: 15diff --git a/scripts/test-type-boot-browser.mjs b/scripts/test-type-boot-browser.mjsnew file mode 100644index 00000000..6fc2adcb--- /dev/null+++ b/scripts/test-type-boot-browser.mjs@@ -0,0 +1,82 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+// bento/type boots on the shell loader's synchronous path, and the fields+// wiring that used to be lazily imported still works.+//+// npm run build:single --prefix type && node scripts/test-type-boot-browser.mjs+//+// The loader runs an app's bundle as an inline CLASSIC script first. A bundle+// containing `import.meta` cannot run that way. fields.ts once had two dynamic+// `import()`s (toc.ts for pageOfY, model.ts for spliceText), and in a+// single-file build Vite compiles those to a helper carrying import.meta.url.+// So every type boot failed the inline path and the next one, threw a page+// error, and started from the loader's last resort. The two pieces now live in+// fieldwire.ts, which imports both statically.+//+// WHAT THIS PROVES, in the packaged document:+// 1. the boot takes the loader's inline path, with no page error;+// 2. after pagination a `page` field far down a long document shows the page+// it is on (not 1), and `pages` shows the page count: the measurement+// fieldwire.ts hooks up still runs;+// 3. ⋯ → "Turn {{…}} tokens into fields" still binds a {{title}} token.+//+// Mutation (run, judged by exit code): restore the dynamic import of toc.ts+// in place of fieldwire.ts's measurement → 1 goes red.+const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')++let checks = 0, failures = 0+const ok = (c, m) => { checks++; if (!c) { failures++; console.log(` FAIL ${m}`) } else console.log(` ok ${m}`) }+const SHELL = process.env.TYPE_SHELL || new URL('../type/dist-single/Bento_Type.bento.html', import.meta.url).href++const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH, headless: true })+try {+ const p = await browser.newPage({ viewport: { width: 1440, height: 900 } })+ const errors = []+ p.on('pageerror', (e) => errors.push(e.message))+ await p.route(/^https?:/, (r) => r.abort())+ await p.goto(SHELL)+ await p.waitForFunction(() => window.bento?.doc)+ const loader = await p.evaluate(() => window.bento.loader)+ ok(loader?.path === 'inline' && errors.length === 0,+ `the boot takes the loader's inline path with no page error (path ${loader?.path}; tried ${JSON.stringify(loader?.tried)}; errors ${JSON.stringify(errors)})`)++ // 2. a long document: a `page` field near the end, a `pages` field at the top+ await p.evaluate(() => {+ const d = JSON.parse(JSON.stringify(window.bento.doc))+ const para = (i, text) => ({ id: `p${i}`, kind: 'para', text })+ const body = [para(0, 'Pages: ')]+ for (let i = 1; i < 90; i++) body.push(para(i, `Paragraph ${i}. ` + 'The quick brown fox jumps over the lazy dog. '.repeat(4)))+ body.push(para(90, 'This is page '))+ body[0].fields = [{ at: 7, name: 'pages' }]+ body[90].fields = [{ at: 13, name: 'page' }]+ d.body = body; d.footnotes = {}+ window.bento.loadDoc(JSON.stringify(d))+ })+ await p.waitForFunction(() => (window.bento.pages?.() ?? window.bento.paginate?.()?.pages?.length ?? 0) && document.querySelector('#paper [data-field="page"]'), null, { timeout: 15000 }).catch(() => {})+ await p.waitForTimeout(1200)+ const f = await p.evaluate(() => ({+ page: document.querySelector('#paper [data-field="page"]')?.textContent?.trim(),+ pages: document.querySelector('#paper [data-field="pages"]')?.textContent?.trim(),+ }))+ ok(Number(f.pages) >= 3, `a "pages" field shows the page count (${f.pages})`)+ ok(Number(f.page) >= 3 && Number(f.page) === Number(f.pages), `a "page" field on the last page shows that page, not 1 (${f.page} of ${f.pages})`)++ // 3. tokens into fields, through the menu+ await p.evaluate(() => {+ const d = JSON.parse(JSON.stringify(window.bento.doc))+ d.title = 'Quarterly report'+ d.body = [{ id: 't1', kind: 'para', text: 'Title: {{title}}.' }]+ window.bento.loadDoc(JSON.stringify(d))+ })+ await p.waitForTimeout(300)+ await p.click('#more')+ await p.getByRole('button', { name: /Turn \{\{…\}\} tokens into fields/ }).or(p.getByRole('menuitem', { name: /Turn \{\{…\}\} tokens into fields/ })).first().click()+ await p.waitForTimeout(400)+ const b = await p.evaluate(() => { const b = window.bento.doc.body[0]; return { text: b.text, fields: (b.fields || []).map((x) => x.name) } })+ ok(b.fields.join() === 'title' && !b.text.includes('{{'), `"Turn {{…}} tokens into fields" binds the token (text ${JSON.stringify(b.text)}, fields ${b.fields})`)+ await p.close()+} finally {+ await browser.close()+}+console.log(`\n${checks - failures}/${checks} checks passed`)+if (failures) process.exit(1)diff --git a/type/src/fields.ts b/type/src/fields.tsindex bcf81c74..e206742e 100644--- a/type/src/fields.ts+++ b/type/src/fields.ts@@ -92,7 +92,7 @@// author can still rename the column.import { t } from './i18n.ts';-import { registerMenuItem, registerPaginated, registerTool, type FeatureContext } from './features.ts';+import { registerTool, type FeatureContext } from './features.ts';// TYPES ONLY from model.ts, and that is load-bearing rather than tidy: model.ts// imports `shiftFields` and `readFieldRefs` from HERE (the same arrangement it// has with xref.ts), so a value import back would be a real evaluation-time@@ -459,28 +459,20 @@ export function setPagination(pages: number | undefined, at: Map<string, number>}/**- * toc.ts's `pageOfY`, fetched LAZILY — and the laziness is load-bearing.+ * After each pagination pass: which page every field sits on. Wired from+ * fieldwire.ts, NOT here, and that placement is load-bearing.** model.ts imports this module, so anything this module imports at the top* joins model.ts's own import graph. toc.ts calls `registerBlockDecorator` at- * MODULE SCOPE, so a static import here closes the cycle+ * MODULE SCOPE, so importing toc here closes the cycle* model → fields → toc → render → model and toc runs against a half-evaluated* render.ts: measured, `Cannot access 'registerBlockDecorator' before- * initialization`, at import time, in every build. Deferring the import to the- * first pagination pass breaks the cycle in time rather than in structure — and- * the alternative, a second copy of "which page is this y on", is exactly what- * would let a field and a table of contents disagree about page 7.+ * initialization`, at import time, in every build. Taking `pageOfY` as an+ * ARGUMENT keeps one copy of "which page is this y on" (a second copy is+ * exactly what would let a field and a table of contents disagree about page+ * 7) without this module importing toc at all.*/-let PAGE_OF_Y: Promise<typeof import('./toc.ts')> | null = null;-const tocModule = () => (PAGE_OF_Y ??= import('./toc.ts'));--registerPaginated((ctx, metrics, paper) => {- const m = metrics as Metrics;- if (!m?.pages?.length) return;- void tocModule().then(({ pageOfY }) => measure(ctx, m, paper, pageOfY));-});--function measure(+export function measure(ctx: FeatureContext,m: Metrics,paper: HTMLElement,@@ -702,22 +694,3 @@ registerTool({run: openFieldPicker,});-registerMenuItem({- id: 'fields-from-tokens',- label: () => t('Turn {{…}} tokens into fields'),- order: 61,- run: ctx => {- // Imported lazily so this module stays free of a value-level cycle with- // model.ts, which imports `shiftFields` from here.- void import('./model.ts').then(({ spliceText }) => {- let n = 0;- ctx.store.breakRun();- ctx.store.commit(d => { n = bindTokens(d, spliceText); });- ctx.editor.render();- ctx.refresh();- ctx.toast(n- ? t('{n} field(s) created from tokens').replace('{n}', String(n))- : t('No {{…}} tokens found in this document'));- });- },-});diff --git a/type/src/fieldwire.ts b/type/src/fieldwire.tsnew file mode 100644index 00000000..6baff148--- /dev/null+++ b/type/src/fieldwire.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The two pieces of fields.ts's feature that need toc.ts or model.ts at RUN+// time, wired from here so fields.ts itself imports neither.+//+// fields.ts is imported BY model.ts, so whatever it imports joins model.ts's+// own import graph: importing toc.ts there closes model → fields → toc →+// render → model, and toc runs against a half-evaluated render.ts (see the+// note above fields.ts `measure`). This module is loaded from registry.ts,+// beside toc.ts, long after model.ts has finished evaluating, so it can import+// all three statically.+//+// These used to be dynamic `import()`s inside fields.ts. In a single-file build+// they compile to Vite's lazy-import helper, which carries `import.meta.url`,+// and a bundle containing that cannot run as a classic script.++import { t } from './i18n.ts';+import { registerMenuItem, registerPaginated } from './features.ts';+import { bindTokens, measure } from './fields.ts';+import { spliceText } from './model.ts';+import { pageOfY } from './toc.ts';+import type { Metrics } from './paginate.ts';++registerPaginated((ctx, metrics, paper) => {+ const m = metrics as Metrics;+ if (!m?.pages?.length) return;+ // a microtask, as when this waited on the lazy import: measuring runs after+ // the pagination pass's other hooks, not in the middle of them+ queueMicrotask(() => measure(ctx, m, paper, pageOfY));+});++registerMenuItem({+ id: 'fields-from-tokens',+ label: () => t('Turn {{…}} tokens into fields'),+ order: 61,+ run: ctx => {+ let n = 0;+ ctx.store.breakRun();+ ctx.store.commit(d => { n = bindTokens(d, spliceText); });+ ctx.editor.render();+ ctx.refresh();+ ctx.toast(n+ ? t('{n} field(s) created from tokens').replace('{n}', String(n))+ : t('No {{…}} tokens found in this document'));+ },+});diff --git a/type/src/registry.ts b/type/src/registry.tsindex 3d948401..47c6324c 100644--- a/type/src/registry.ts+++ b/type/src/registry.ts@@ -28,6 +28,7 @@ import './math.ts'; // mathematics: inline formulas and display equationsexport {};import './link.ts';import './toc.ts'; // section numbering + table of contents+import './fieldwire.ts'; // fields' page numbers + "Turn {{…}} tokens into fields" (after toc)// comments — margin notes on a range of text, with replies and resolution.// Anchors ride inline.ts `shift`, so they move exactly as marks and footnote// anchors do; nothing here can reach print (see the header of comments.ts).