@crossworks/app-build 0.400.74 → 0.500.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crossworks/app-build",
3
- "version": "0.400.74",
3
+ "version": "0.500.1",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "types": "./src/index.ts",
@@ -14,7 +14,7 @@
14
14
  "@babel/parser": "7.29.9",
15
15
  "@dnd-kit/core": "6.3.1",
16
16
  "@dnd-kit/sortable": "10.0.0",
17
- "@mantle/share-ui": "npm:@crossworks/share-ui@0.400.74",
17
+ "@mantle/share-ui": "npm:@crossworks/share-ui@0.500.1",
18
18
  "@tailwindcss/oxide": "^4.3.3",
19
19
  "@tanstack/react-table": "9.3.1",
20
20
  "@tanstack/react-virtual": "3.14.24",
@@ -21,6 +21,7 @@ import { APP_CANVAS_LIBRARIES, APP_LIBRARY_SPECIFIERS } from './app-libraries';
21
21
  import { buildCanvasRuntime } from './canvas-runtime';
22
22
  import { buildRuntime, type RuntimeManifest } from './build-runtime';
23
23
  import { buildApp } from './index';
24
+ import { appLibraryScripts } from '@mantle/share-ui/app-frame-html';
24
25
  import { LIBRARY_EXPORTS_FIXTURE } from './runtime-exports.fixture';
25
26
 
26
27
  const ROOT = path.resolve(__dirname, '../../..');
@@ -97,6 +98,12 @@ describe('the app libraries, against the real runtimes', () => {
97
98
  }
98
99
  });
99
100
 
101
+ it('the app frame CSP allows every library file the app import map names', () => {
102
+ const lib = Object.values(app.imports).filter((u) => u.startsWith('/canvas-runtime/'));
103
+ expect(lib.length).toBeGreaterThan(0);
104
+ expect(appLibraryScripts(app.imports)).toEqual([...new Set(lib)].sort());
105
+ });
106
+
100
107
  it('there is a sample for every library', () => {
101
108
  expect(Object.keys(SAMPLES).every((s) => APP_LIBRARY_SPECIFIERS.includes(s))).toBe(true);
102
109
  });
package/src/build.test.ts CHANGED
@@ -188,6 +188,34 @@ describe('buildApp — the import allowlist (security boundary)', () => {
188
188
  }
189
189
  });
190
190
 
191
+ it("says nothing of the server's paths when an app's own CSS reaches a package file", async () => {
192
+ const res = await buildApp(
193
+ app({
194
+ 'App.tsx':
195
+ 'import \'./s.css\';\nexport default function App() { return <p className="a">x</p>; }\n',
196
+ 's.css': '.a { background: url(lucide-react/package.json); }\n',
197
+ }),
198
+ { runtimeExports: RT },
199
+ );
200
+ const said = JSON.stringify([...res.errors, ...res.warnings]);
201
+ expect(said).not.toContain('node_modules');
202
+ expect(said).not.toMatch(/\/(?:Users|Volumes|app|home)\//);
203
+ // The message keeps its place in the app, with the path put as <server file>.
204
+ const at = res.errors.find((e) => e.location?.file.endsWith('s.css'));
205
+ expect(at?.text).toContain('<server file>');
206
+ });
207
+
208
+ it('refuses a file it cannot parse', async () => {
209
+ const res = await buildApp(
210
+ app({
211
+ 'App.tsx': "import { nope } from '@host';\nlet = ;\nexport default function App() {}\n",
212
+ }),
213
+ { runtimeExports: RT },
214
+ );
215
+ expect(res.ok).toBe(false);
216
+ expect(res.errors.length).toBeGreaterThan(0);
217
+ });
218
+
191
219
  it("keeps a warning about the app's own code, even when it quotes a path-like key", async () => {
192
220
  const res = await buildApp(
193
221
  app({
package/src/index.ts CHANGED
@@ -311,6 +311,24 @@ const DISK_READ_RE = /Cannot read (file|directory)|No loader is configured|Could
311
311
  * `C:\\x`. Not `"/"` alone, which a plain syntax error quotes. */
312
312
  const OUTSIDE_PATH_RE = /(?:^|[\s"'(:])(?:\.\.[\\/]|\/[^\s"'/]+\/|[A-Za-z]:[\\/])/;
313
313
  const GENERIC_MSG = 'The build failed on a file that is not part of this app.';
314
+ /** The workspace this server runs from (packages/app-build/src, three up):
315
+ * any path under it is a server path. */
316
+ const SERVER_ROOT = path.resolve(REAL_DIR, '..', '..', '..');
317
+ /** A message located in the app that still quotes a server path: one under
318
+ * node_modules, or under the workspace root. An app's own text that only
319
+ * looks like a path (`"/api/v1/"`, `../lib/x`) is kept. */
320
+ function quotesServerPath(text: string): boolean {
321
+ return text.includes('node_modules') || text.includes(SERVER_ROOT + path.sep);
322
+ }
323
+ /** One quoted or bare path that names node_modules or the workspace root. */
324
+ const SERVER_PATH_RE = new RegExp(
325
+ `[^\\s"'\`()]*(?:node_modules|${(SERVER_ROOT + path.sep).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})[^\\s"'\`()]*`,
326
+ 'g',
327
+ );
328
+ /** The text with each server path it quotes put as `<server file>`. */
329
+ function scrubServerPaths(text: string): string {
330
+ return text.replace(SERVER_PATH_RE, '<server file>');
331
+ }
314
332
 
315
333
  /**
316
334
  * A build message the author may see. One about the app's own code (located
@@ -325,13 +343,23 @@ function appOnlyMsg(source: AppSource, m: Message): BuildMessage {
325
343
  if (!file) {
326
344
  return OUTSIDE_PATH_RE.test(m.text) ? { text: GENERIC_MSG, location: null } : toMsg(m);
327
345
  }
328
- if (file === STDIN || file.endsWith(`/${STDIN}`)) return toMsg(m);
346
+ // From here the message is located in the app's own source, but its text
347
+ // can still quote a server path: a CSS url() that names a package file
348
+ // gets one at `app:s.css`. That path reads `<server file>`; the rest of the
349
+ // message and its place in the app stay, so the author can find the line.
350
+ const ownMsg = (): BuildMessage => {
351
+ if (!quotesServerPath(m.text)) return toMsg(m);
352
+ const text = scrubServerPaths(m.text);
353
+ return quotesServerPath(text) ? { text: GENERIC_MSG, location: null } : { ...toMsg(m), text };
354
+ };
355
+ if (file === STDIN || file.endsWith(`/${STDIN}`)) return ownMsg();
329
356
  // An app file is located as `app:<key>` (its namespace). A bare path that
330
357
  // merely equals a file key is a disk file, not the app's (the M2's C2).
331
358
  if (file.startsWith(`${APP_NS}:`) && Object.hasOwn(source.files, file.slice(APP_NS.length + 1))) {
332
- return toMsg(m);
359
+ return ownMsg();
333
360
  }
334
- if (path.resolve(file).startsWith(LUCIDE_ROOT + path.sep)) return toMsg(m);
361
+ // A lucide-react file is the server's: the text may stay, its path not.
362
+ if (path.resolve(file).startsWith(LUCIDE_ROOT + path.sep)) return { ...ownMsg(), location: null };
335
363
  return { text: GENERIC_MSG, location: null };
336
364
  }
337
365
 
@@ -505,59 +533,77 @@ export function lintToolRefs(source: AppSource, declaredSlugs: string[]): BuildM
505
533
  return out;
506
534
  }
507
535
 
508
- /** `import <what> from "<spec>"` — captures the clause and the specifier.
509
- * Covers the three ESM shapes esbuild leaves external: default, namespace,
510
- * and named (including a default+named combination). */
511
- const IMPORT_RE = /import\s+([^'";]+?)\s+from\s*['"]([^'"]+)['"]/g;
512
-
513
- /** A re-export links like an import: `export { a } from 'm'`,
514
- * `export type { A } from 'm'`, `export * as ns from 'm'`. Only these exact
515
- * shapes (the clause runs to `from` with nothing between), so an `export`
516
- * statement without a `from` never reaches over to a later import.
517
- * `export * from 'm'` names nothing and is left alone. */
518
- const REEXPORT_RE =
519
- /export\s+((?:type\s*)?\{[^}]*\}|\*\s+as\s+[A-Za-z_$][\w$]*)\s*from\s*['"]([^'"]+)['"]/g;
520
-
521
- /** `import type …` — the whole clause is type-only. Lookahead keeps
522
- * `import type from 'm'` and `import type, { a } from 'm'` (a default import
523
- * that happens to be NAMED `type`) as value imports. */
524
- const TYPE_ONLY_CLAUSE_RE = /^type(?=\s*[{*]|\s+[A-Za-z_$])/;
525
-
526
- /** `{ type X }` / `{ type X as Y }` — one type-only specifier. `{ type }` and
527
- * `{ type as t }` import a value named `type` and stay checked. */
528
- const TYPE_ONLY_SPECIFIER_RE = /^type\s+(?!as\b)[A-Za-z_$]/;
529
-
530
- /** Split an import clause into the names it binds FROM the module.
531
- * `Foo` → default
532
- * `* as ns` → namespace (binds nothing by name; nothing to check)
533
- * `{ a, b as c }` → a, b
534
- * `Foo, { a }` → default, a
535
- * `type { A }` → nothing (type-only)
536
- * `{ type A, b }` → b
537
- * Returns the names as the MODULE must provide them, not the local aliases.
538
- * Type-only imports and specifiers are skipped: the compiler erases them, so
539
- * they never reach the runtime and cannot fail to link. */
540
- function importedNames(clause: string): { names: string[]; namespace: boolean } {
541
- const names: string[] = [];
542
- let namespace = false;
543
- if (TYPE_ONLY_CLAUSE_RE.test(clause)) return { names, namespace };
544
- const braced = clause.match(/\{([^}]*)\}/);
545
- const head = clause
546
- .slice(0, braced ? clause.indexOf('{') : undefined)
547
- .replace(/,\s*$/, '')
548
- .trim();
549
- if (head) {
550
- if (/^\*\s+as\s+/.test(head)) namespace = true;
551
- else if (/^[A-Za-z_$][\w$]*$/.test(head)) names.push('default');
536
+ /** One import or re-export of a module, as the module must answer it: the
537
+ * specifier, the names it must export (`default` for a default import), and
538
+ * where the statement starts. */
539
+ type ModuleImport = { spec: string; names: string[]; line: number; column: number };
540
+
541
+ type AstNode = {
542
+ type: string;
543
+ loc?: { start: { line: number; column: number } };
544
+ [k: string]: unknown;
545
+ };
546
+
547
+ /** An import's or export's name node: an identifier, or a string name
548
+ * (`import { 'a-b' as c }`). */
549
+ function nameOf(node: unknown): string | null {
550
+ const n = node as { type?: string; name?: string; value?: string } | undefined;
551
+ if (n?.type === 'Identifier') return n.name ?? null;
552
+ if (n?.type === 'StringLiteral') return n.value ?? null;
553
+ return null;
554
+ }
555
+
556
+ /**
557
+ * The static imports and re-exports of one file, read from its parsed source
558
+ * (Babel, TypeScript and JSX, as written), so an escaped name or specifier
559
+ * (`import { \u0068ost } from '\u0040host'`) reads as what it is. Type-only
560
+ * imports and specifiers are left out: the compiler erases them, so they
561
+ * never reach the runtime and cannot fail to link. A namespace import or
562
+ * `export *` binds nothing by name, so there is nothing to check. Null when
563
+ * the file does not parse: computedImportErrors refuses that build anyway.
564
+ */
565
+ function moduleImports(file: string, text: string): ModuleImport[] | null {
566
+ let ast: { program: { body: AstNode[] } };
567
+ try {
568
+ ast = parse(text, {
569
+ sourceType: 'module',
570
+ sourceFilename: file,
571
+ plugins: parserPlugins(loaderFor(file)),
572
+ createImportExpressions: true,
573
+ errorRecovery: false,
574
+ }) as unknown as { program: { body: AstNode[] } };
575
+ } catch {
576
+ return null;
552
577
  }
553
- if (braced) {
554
- for (const part of braced[1]!.split(',')) {
555
- if (TYPE_ONLY_SPECIFIER_RE.test(part.trim())) continue;
556
- const name = (part.split(/\s+as\s+/)[0] ?? '').trim();
557
- if (name) names.push(name);
578
+ const out: ModuleImport[] = [];
579
+ for (const node of ast.program.body) {
580
+ const source = (node.source as { value?: string } | null | undefined)?.value;
581
+ if (typeof source !== 'string') continue;
582
+ const at = { line: node.loc?.start.line ?? 0, column: node.loc?.start.column ?? 0 };
583
+ if (node.type === 'ImportDeclaration') {
584
+ if (node.importKind === 'type') continue;
585
+ const names: string[] = [];
586
+ for (const sp of (node.specifiers as AstNode[]) ?? []) {
587
+ if (sp.type === 'ImportDefaultSpecifier') names.push('default');
588
+ else if (sp.type === 'ImportSpecifier' && sp.importKind !== 'type') {
589
+ const name = nameOf(sp.imported);
590
+ if (name) names.push(name);
591
+ }
592
+ }
593
+ out.push({ spec: source, names, ...at });
594
+ } else if (node.type === 'ExportNamedDeclaration') {
595
+ if (node.exportKind === 'type') continue;
596
+ const names: string[] = [];
597
+ for (const sp of (node.specifiers as AstNode[]) ?? []) {
598
+ if (sp.type === 'ExportSpecifier' && sp.exportKind !== 'type') {
599
+ const name = nameOf(sp.local);
600
+ if (name) names.push(name);
601
+ }
602
+ }
603
+ out.push({ spec: source, names, ...at });
558
604
  }
559
605
  }
560
- return { names, namespace };
606
+ return out;
561
607
  }
562
608
 
563
609
  /** A module's export names for an error. A large surface (mathjs exports
@@ -602,31 +648,22 @@ export function lintRuntimeImports(
602
648
  ): BuildMessage[] {
603
649
  const out: BuildMessage[] = [];
604
650
  for (const [file, text] of Object.entries(source.files)) {
605
- for (const re of [IMPORT_RE, REEXPORT_RE]) {
606
- re.lastIndex = 0;
607
- let m: RegExpExecArray | null;
608
- while ((m = re.exec(text)) !== null) {
609
- const spec = m[2]!;
610
- if (spec.startsWith('.') || spec.startsWith('/')) continue;
611
- const available = runtimeExports[spec];
612
- if (!available) continue; // not a shared-runtime specifier; esbuild will rule on it
613
- const { names, namespace } = importedNames(m[1]!);
614
- if (namespace) continue;
615
- const have = new Set(available);
616
- for (const name of names) {
617
- if (have.has(name)) continue;
618
- const pre = text.slice(0, m.index);
619
- const line = pre.length - pre.replace(/\n/g, '').length + 1; // 1-based
620
- const column = m.index - (pre.lastIndexOf('\n') + 1); // 0-based within line
621
- const hint =
622
- name === 'default'
623
- ? `'${spec}' has no default export. Use a named import, e.g. import { ${available[0]} } from '${spec}'.`
624
- : `'${spec}' does not export '${name}'.`;
625
- out.push({
626
- text: `${hint} It exports: ${exportList(available, name)}. Left as-is the app builds but fails to load in the browser, with no error the app can catch.`,
627
- location: { file, line, column },
628
- });
629
- }
651
+ if (!CODE_LOADERS.has(loaderFor(file))) continue;
652
+ for (const { spec, names, line, column } of moduleImports(file, text) ?? []) {
653
+ if (spec.startsWith('.') || spec.startsWith('/')) continue;
654
+ const available = runtimeExports[spec];
655
+ if (!available) continue; // not a shared-runtime specifier; esbuild will rule on it
656
+ const have = new Set(available);
657
+ for (const name of names) {
658
+ if (have.has(name)) continue;
659
+ const hint =
660
+ name === 'default'
661
+ ? `'${spec}' has no default export. Use a named import, e.g. import { ${available[0]} } from '${spec}'.`
662
+ : `'${spec}' does not export '${name}'.`;
663
+ out.push({
664
+ text: `${hint} It exports: ${exportList(available, name)}. Left as-is the app builds but fails to load in the browser, with no error the app can catch.`,
665
+ location: { file, line, column },
666
+ });
630
667
  }
631
668
  }
632
669
  }
@@ -23,6 +23,25 @@ describe('lintRuntimeImports', () => {
23
23
  expect(msgs[0]!.location).toEqual({ file: 'lib/store.ts', line: 1, column: 0 });
24
24
  });
25
25
 
26
+ it('reads an escaped name or specifier as what it is (the parsed source, not a regex)', () => {
27
+ // \u0068ost is host and \u0040host is @host: the browser links them so.
28
+ expect(
29
+ lintRuntimeImports(src({ 'a.ts': "import { \\u0068ost } from '\\u0040host';\n" }), RT),
30
+ ).toEqual([]);
31
+ const msgs = lintRuntimeImports(
32
+ src({ 'a.ts': "import { \\u006eope } from '\\u0040host';\n" }),
33
+ RT,
34
+ );
35
+ expect(msgs).toHaveLength(1);
36
+ expect(msgs[0]!.text).toContain("'@host' does not export 'nope'");
37
+ });
38
+
39
+ it('skips a file it cannot parse (the computed-import check refuses that build)', () => {
40
+ expect(
41
+ lintRuntimeImports(src({ 'a.ts': "import { nope } from '@host';\nlet = ;\n" }), RT),
42
+ ).toEqual([]);
43
+ });
44
+
26
45
  it('accepts the correct named import', () => {
27
46
  expect(lintRuntimeImports(src({ 'a.ts': "import { host } from '@host';\n" }), RT)).toEqual([]);
28
47
  });