@bedrock-core/builder 0.1.2 → 0.3.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +84 -1
  2. package/dist/bin/api-library.d.ts +1 -0
  3. package/dist/bin/api-library.js +10 -0
  4. package/dist/bin/audit-paths.d.ts +1 -0
  5. package/dist/bin/audit-paths.js +44 -0
  6. package/dist/bin/build.js +1 -1
  7. package/dist/bin/builder.js +13 -2
  8. package/dist/bin/migrate.js +1 -15
  9. package/dist/bin/plan.js +2 -2
  10. package/dist/bin/watch.js +1 -1
  11. package/dist/package.json +12 -10
  12. package/dist/schemas/bundler.schema.json +5 -0
  13. package/dist/schemas/config.schema.json +40 -10
  14. package/dist/schemas/generator.schema.json +11 -29
  15. package/dist/schemas/guides.schema.json +0 -5
  16. package/dist/schemas/i18n.schema.json +0 -5
  17. package/dist/schemas/pack-manifest.schema.json +294 -0
  18. package/dist/schemas/ui-compiler.schema.json +0 -15
  19. package/dist/src/config.d.ts +21 -7
  20. package/dist/src/config.js +3 -0
  21. package/dist/src/contract.d.ts +5 -2
  22. package/dist/src/export.d.ts +7 -5
  23. package/dist/src/export.js +274 -47
  24. package/dist/src/migrate.d.ts +1 -1
  25. package/dist/src/migrate.js +23 -17
  26. package/dist/src/migration/exports.js +1 -1
  27. package/dist/src/migration/filters.d.ts +4 -7
  28. package/dist/src/migration/filters.js +41 -234
  29. package/dist/src/migration/project.d.ts +1 -2
  30. package/dist/src/migration/project.js +35 -25
  31. package/dist/src/migration/types.d.ts +1 -8
  32. package/dist/src/path-audit.d.ts +29 -0
  33. package/dist/src/path-audit.js +110 -0
  34. package/dist/src/plan.d.ts +1 -0
  35. package/dist/src/plan.js +7 -7
  36. package/dist/src/plugin-routing.js +1 -1
  37. package/dist/src/plugins.js +10 -1
  38. package/dist/src/project.d.ts +1 -3
  39. package/dist/src/project.js +1 -12
  40. package/dist/src/regolith.d.ts +3 -3
  41. package/dist/src/regolith.js +26 -4
  42. package/dist/src/run.js +86 -38
  43. package/dist/src/staging.d.ts +4 -0
  44. package/dist/src/staging.js +305 -0
  45. package/dist/src/validation.d.ts +1 -1
  46. package/dist/src/watch.js +48 -29
  47. package/package.json +41 -20
  48. package/schemas/bundler.schema.json +5 -0
  49. package/schemas/config.schema.json +40 -10
  50. package/schemas/generator.schema.json +11 -29
  51. package/schemas/guides.schema.json +0 -5
  52. package/schemas/i18n.schema.json +0 -5
  53. package/schemas/pack-manifest.schema.json +294 -0
  54. package/schemas/ui-compiler.schema.json +0 -15
  55. package/dist/src/migration/local-filter.d.ts +0 -3
  56. package/dist/src/migration/local-filter.js +0 -20
package/dist/src/plan.js CHANGED
@@ -1,5 +1,5 @@
1
- import { builtinPlugins } from "./builtins.js";
2
- import { validatePluginDefinition } from "./config.js";
1
+ import { builtinPlugins } from './builtins.js';
2
+ import { validatePluginDefinition } from './config.js';
3
3
  /** Ordered built-in boundaries; automatic input detection happens during execution. */
4
4
  export const stages = Object.freeze(Object.keys(builtinPlugins));
5
5
  const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -81,10 +81,10 @@ export function planBuild(config, profileName = 'default') {
81
81
  if (step.mode !== undefined && step.mode !== 'auto' && step.mode !== 'always') {
82
82
  throw new Error(`Invalid plugin mode: ${step.plugin}`);
83
83
  }
84
- if ('script' in definition && step.mode === 'auto') {
84
+ if (!('module' in definition) && step.mode === 'auto') {
85
85
  throw new Error(`Automatic detection requires a module plugin: ${step.plugin}`);
86
86
  }
87
- if ('script' in definition && (step.packs !== undefined || step.links !== undefined)) {
87
+ if (!('module' in definition) && (step.packs !== undefined || step.links !== undefined)) {
88
88
  throw new Error(`Pack and link overrides require a native module plugin: ${step.plugin}`);
89
89
  }
90
90
  if ('module' in definition && (step.packs !== undefined || step.links !== undefined)) {
@@ -101,9 +101,9 @@ export function planBuild(config, profileName = 'default') {
101
101
  if ('module' in definition && Object.keys(scriptOverrides).length) {
102
102
  throw new Error(`Folder and data overrides require a Node script: ${step.plugin}`);
103
103
  }
104
- const script = 'script' in definition
105
- ? validatePluginDefinition({ ...definition, ...scriptOverrides }, step.plugin)
106
- : undefined;
104
+ const script = 'module' in definition
105
+ ? undefined
106
+ : validatePluginDefinition({ ...definition, ...scriptOverrides }, step.plugin);
107
107
  if (script?.persistData && script.dataPath === undefined) {
108
108
  throw new Error(`Persistent Node data requires an explicit dataPath: ${step.plugin}`);
109
109
  }
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { readdir, readFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { resolvePluginPacks } from "./plugin-packs.js";
4
+ import { resolvePluginPacks } from './plugin-packs.js';
5
5
  /** Preserve live host services while exposing one declared invocation's pack paths. */
6
6
  export function packContext(context, packs, owner, linkedPacks = Object.freeze({}), owners = packs.map(pack => pack.id), routing) {
7
7
  return Object.freeze({
@@ -1,5 +1,14 @@
1
- var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx, extraExtensions, ignoreCase) {
2
2
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ if (extraExtensions) {
4
+ for (var extension in extraExtensions) {
5
+ var suffix = path.slice(-extension.length);
6
+ if (suffix === extension || ignoreCase && suffix.toLowerCase() === extension.toLowerCase()) {
7
+ var output = extraExtensions[extension];
8
+ return output === extension ? path : path.slice(0, -extension.length) + output;
9
+ }
10
+ }
11
+ }
3
12
  return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
13
  return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
14
  });
@@ -1,6 +1,4 @@
1
- import type { ProjectMetadata, BuildContext } from '@bedrock-core/builder-plugin';
1
+ import type { ProjectMetadata } from '@bedrock-core/builder-plugin';
2
2
  import type { ProjectConfig } from './config.ts';
3
3
  /** Resolve shared display and package metadata without importing project code. */
4
4
  export declare function resolveProject(config: ProjectConfig, root: string, dependency?: (file: string) => void): Promise<ProjectMetadata>;
5
- /** Emit shared project metadata and literal editor declarations. */
6
- export declare function generateProject(context: BuildContext, project: ProjectMetadata): Promise<void>;
@@ -1,4 +1,4 @@
1
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
1
+ import { readFile } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { isManifestVersion } from '@bedrock-core/builder-manifest';
4
4
  /** Resolve shared display and package metadata without importing project code. */
@@ -49,7 +49,6 @@ export async function resolveProject(config, root, dependency = () => { }) {
49
49
  }
50
50
  const url = [pkg.homepage, pkg.url].find((value) => typeof value === 'string' && !!value.trim());
51
51
  return Object.freeze({
52
- namespace: config.namespace,
53
52
  name: config.name,
54
53
  description: config.description ?? '',
55
54
  authors: Object.freeze(config.authors.map(author => typeof author === 'string' ? author : author.name)),
@@ -60,13 +59,3 @@ export async function resolveProject(config, root, dependency = () => { }) {
60
59
  ...(url ? { url: url.trim() } : {}),
61
60
  });
62
61
  }
63
- /** Emit shared project metadata and literal editor declarations. */
64
- export async function generateProject(context, project) {
65
- const value = JSON.stringify(project);
66
- const file = path.join(context.generatedDir, 'project.js');
67
- const declarations = path.join(context.projectRoot, '.bedrock-core/generated/project.d.ts');
68
- await writeFile(file, `export const project = ${value};\n`);
69
- await mkdir(path.dirname(declarations), { recursive: true });
70
- await writeFile(declarations, `declare module '@bedrock-core/generated/project' {\n export const project: ${value};\n}\n`);
71
- await context.registerArtifact('project:metadata', file, { importAs: '@bedrock-core/generated/project' });
72
- }
@@ -1,10 +1,10 @@
1
1
  import type { BuildContext } from './contract.d.ts';
2
2
  import type { NodePluginDefinition, Settings } from './config.ts';
3
- interface NodeFilterOptions extends NodePluginDefinition {
3
+ type NodeFilterOptions = NodePluginDefinition & {
4
4
  settings?: Settings;
5
5
  arguments?: string[];
6
- }
7
- /** Run a standalone Regolith Node script against conventional staged BP, RP and data folders. */
6
+ };
7
+ /** Run a Node entry against conventional staged BP, RP and data folders. */
8
8
  export declare function runNodeFilter(context: BuildContext, options: NodeFilterOptions, sharedContext?: BuildContext): Promise<void>;
9
9
  /** Publish opted-in data with pack publication, restoring authored data if publication fails. */
10
10
  export declare function publishNodeData<T>(context: BuildContext, publish: () => Promise<T>): Promise<T>;
@@ -1,9 +1,12 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm } from 'node:fs/promises';
4
+ import { createRequire, isBuiltin } from 'node:module';
4
5
  import path from 'node:path';
5
6
  import { createInterface } from 'node:readline';
6
- import { withSourceWrites } from "./source-writes.js";
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { resolve } from 'import-meta-resolve';
9
+ import { withSourceWrites } from './source-writes.js';
7
10
  const sessions = new WeakMap();
8
11
  const roles = ['BP', 'RP'];
9
12
  function contains(root, file) {
@@ -191,11 +194,30 @@ async function execute(context, options, directory, script, filterDir) {
191
194
  });
192
195
  });
193
196
  }
194
- /** Run a standalone Regolith Node script against conventional staged BP, RP and data folders. */
197
+ function moduleEntry(specifier, filterDir) {
198
+ if (specifier.startsWith('.') || path.isAbsolute(specifier) || specifier.includes(':') || isBuiltin(specifier)) {
199
+ throw new Error('Node filter module must be a package specifier: ' + specifier);
200
+ }
201
+ const parent = pathToFileURL(path.join(filterDir, 'package.json'));
202
+ try {
203
+ return fileURLToPath(resolve(specifier, parent.href));
204
+ }
205
+ catch (error) {
206
+ try {
207
+ return createRequire(parent).resolve(specifier);
208
+ }
209
+ catch {
210
+ throw new Error('Cannot resolve Node filter module ' + specifier + ' from ' + filterDir, { cause: error });
211
+ }
212
+ }
213
+ }
214
+ /** Run a Node entry against conventional staged BP, RP and data folders. */
195
215
  export async function runNodeFilter(context, options, sharedContext = context) {
196
216
  context.signal?.throwIfAborted();
197
217
  const filterDir = await realpath(path.resolve(context.projectRoot, options.filterDir ?? '.'));
198
- const script = await realpath(path.resolve(filterDir, options.script));
218
+ const script = await realpath(options.nodeModule === undefined
219
+ ? path.resolve(filterDir, options.script)
220
+ : moduleEntry(options.nodeModule, filterDir));
199
221
  if (!(await lstat(script)).isFile()) {
200
222
  throw new Error('Node filter script must be a file: ' + script);
201
223
  }
@@ -245,7 +267,7 @@ export async function publishNodeData(context, publish) {
245
267
  for (const session of selected) {
246
268
  const source = session.dataSource;
247
269
  const parts = path.relative(context.projectRoot, source).split(path.sep);
248
- const roots = [...Object.values(context.allPacks ?? context.packs).map(directory => path.join(context.projectRoot, path.relative(context.stagedRoot, directory))), ...Object.values(context.outputPaths)];
270
+ const roots = [...Object.values(context.allPacks ?? context.packs).map(directory => path.join(context.projectRoot, path.relative(context.stagedRoot, directory))), ...Object.values(context.outputPaths), ...(context.apiOutput ? [context.apiOutput] : [])];
249
271
  if (!contains(context.projectRoot, source) || source === context.projectRoot
250
272
  || parts.some(part => ['.git', 'node_modules', '.bedrock-core'].includes(part) || part.includes('.builder-'))
251
273
  || roots.some(root => contains(root, source) || contains(source, root))) {
package/dist/src/run.js CHANGED
@@ -3,21 +3,21 @@ import { tmpdir } from 'node:os';
3
3
  import path from 'node:path';
4
4
  import { createRequire } from 'node:module';
5
5
  import { pathToFileURL } from 'node:url';
6
- import { validateConfig } from "./config.js";
7
- import { isStagingExcluded, stagingExclusions } from "./staging.js";
8
- import { planBuild } from "./plan.js";
9
- import { resolveProject, generateProject } from "./project.js";
10
- import { runNodeFilter, publishNodeData } from "./regolith.js";
11
- import { builtinPlugins } from "./builtins.js";
12
- import { loadPlugin, executePlugin } from "./plugins.js";
13
- import { nativePluginContexts, sharedPackWrites } from "./plugin-routing.js";
14
- import { inspectPacks } from "./packs.js";
6
+ import { validateConfig } from './config.js';
7
+ import { isStagingExcluded, isStagingInput, stagingExclusions, stagingInputs } from './staging.js';
8
+ import { planBuild } from './plan.js';
9
+ import { resolveProject } from './project.js';
10
+ import { runNodeFilter, publishNodeData } from './regolith.js';
11
+ import { builtinPlugins } from './builtins.js';
12
+ import { loadPlugin, executePlugin } from './plugins.js';
13
+ import { nativePluginContexts, sharedPackWrites } from './plugin-routing.js';
14
+ import { inspectPacks } from './packs.js';
15
15
  import { describePack, resolvePackGraph } from '@bedrock-core/builder-plugin';
16
- import { resolveManifest, resolveProjectManifests } from '@bedrock-core/builder-manifest';
17
- import { validatePackManifests } from "./manifest.js";
18
- import { resolveExportPaths, withExportPaths } from "./export.js";
16
+ import { resolveManifest, resolveProjectManifests, hasApiExports } from '@bedrock-core/builder-manifest';
17
+ import { finalizePackManifests, prepareAddonArtwork, validatePackManifests } from './manifest.js';
18
+ import { resolveExportPaths, resolveApiPackagePath, withExportPaths } from './export.js';
19
19
  import { createHash } from 'node:crypto';
20
- import { createFileCache, trackLocations } from "./file-cache.js";
20
+ import { createFileCache, trackLocations } from './file-cache.js';
21
21
  import { validatePackContent } from '@bedrock-core/builder-validation';
22
22
  const inside = (root, file) => {
23
23
  const relative = path.relative(root, file);
@@ -67,12 +67,20 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
67
67
  throw new Error('Profile needs export destinations for its packs to execute a build');
68
68
  }
69
69
  const outputPaths = Object.freeze(resolveExportPaths(project, config.packs, exportConfig));
70
+ const packageFile = path.join(project, 'package.json');
71
+ const packageMetadata = await exists(packageFile) ? JSON.parse(await readFile(packageFile, 'utf8')) : undefined;
72
+ const hasPublicApi = hasApiExports(packageMetadata);
73
+ const apiSelection = config.bedrockCore.profiles[profile]?.api;
74
+ const apiOutput = hasPublicApi && apiSelection !== false
75
+ ? resolveApiPackagePath(project, config.packs, outputPaths, apiSelection ?? 'dist/api')
76
+ : undefined;
70
77
  const outputs = Object.values(config.bedrockCore.profiles).flatMap((settings) => {
71
78
  if (!settings.export) {
72
79
  return [];
73
80
  }
74
81
  try {
75
- return Object.values(resolveExportPaths(project, config.packs, settings.export));
82
+ const paths = resolveExportPaths(project, config.packs, settings.export);
83
+ return [...Object.values(paths), ...(hasPublicApi && settings.api !== false ? [resolveApiPackagePath(project, config.packs, paths, settings.api ?? 'dist/api')] : [])];
76
84
  }
77
85
  catch {
78
86
  return [];
@@ -99,7 +107,7 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
99
107
  const require = createRequire(file);
100
108
  const modules = new Map();
101
109
  for (const step of plan.filter(step => step.kind === 'plugin')) {
102
- if (step.script !== undefined) {
110
+ if (step.module === undefined) {
103
111
  continue;
104
112
  }
105
113
  const local = step.module.startsWith('.') || path.isAbsolute(step.module);
@@ -113,26 +121,23 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
113
121
  const ignored = new Set(['.git', 'node_modules', '.bedrock-core']);
114
122
  const normalized = (file) => process.platform === 'win32' ? file.toLowerCase() : file;
115
123
  const isOutput = (file) => outputs.some(output => path.relative(output, file) === '' || normalized(file).startsWith(`${normalized(output)}.builder-`));
116
- // Reject symlinks before copying or publishing, including export parent directories.
117
- async function inspect(directory, skipIgnored = true) {
124
+ const sources = await stagingInputs(project, config, profile, file, outputs, signal);
125
+ async function inspect(directory) {
118
126
  for (const entry of await readdir(directory, { withFileTypes: true })) {
119
127
  const source = path.join(directory, entry.name);
120
- if (skipIgnored && (isOutput(source) || ignored.has(entry.name) || isStagingExcluded(source, exclusions))) {
121
- continue;
122
- }
123
128
  if (entry.isSymbolicLink()) {
124
129
  throw new Error(`Symlinks are unsupported in staged sources: ${source}`);
125
130
  }
126
131
  if (entry.isDirectory()) {
127
- await inspect(source, skipIgnored);
132
+ await inspect(source);
128
133
  }
129
134
  }
130
135
  }
131
- await inspect(project);
132
136
  return withExportPaths(outputPaths, async (publish) => {
133
137
  let workspace;
134
- const dependencies = new Set([file, ...metadataInputs, ...modules.values()]);
138
+ const dependencies = new Set([file, ...sources, ...metadataInputs, ...modules.values(), ...(hasPublicApi ? [packageFile] : [])]);
135
139
  const artifacts = new Map();
140
+ const artifactFinalizers = new Map();
136
141
  const generatedImports = new Map();
137
142
  const packImports = new Map();
138
143
  const exportExclusions = new Set();
@@ -146,7 +151,7 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
146
151
  const staged = path.join(workspace, 'project');
147
152
  await cp(project, staged, {
148
153
  recursive: true,
149
- filter: source => !isOutput(source) && !ignored.has(path.basename(source)) && !isStagingExcluded(source, exclusions),
154
+ filter: source => isStagingInput(source, sources) && !isOutput(source) && !ignored.has(path.basename(source)) && !isStagingExcluded(source, exclusions),
150
155
  });
151
156
  const generated = path.join(workspace, 'generated');
152
157
  await mkdir(generated);
@@ -175,7 +180,7 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
175
180
  dependencies.add(path.join(project, path.relative(staged, input)));
176
181
  }
177
182
  }
178
- const resolved = resolveProjectManifests(manifests, metadata);
183
+ const resolved = resolveProjectManifests(manifests, metadata, { dependencyRoot: project, registerDependency: input => dependencies.add(input) });
179
184
  return withDestinations(resolvePackGraph(Object.entries(stagedPacks).map(([id, directory]) => describePack(id, directory, resolved[id]))));
180
185
  }
181
186
  let owner = 'prepare';
@@ -205,7 +210,6 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
205
210
  });
206
211
  const context = Object.freeze({
207
212
  projectRoot: project,
208
- namespace: metadata.namespace,
209
213
  project: metadata,
210
214
  stagedRoot: staged,
211
215
  generatedDir: generated,
@@ -216,6 +220,9 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
216
220
  get inputDirectories() {
217
221
  return Object.freeze([...inputDirectories]);
218
222
  },
223
+ get assetRegistryExclusions() {
224
+ return Object.freeze([...artifacts.values()].filter(artifact => artifact.assetRegistry === false).map(artifact => artifact.path));
225
+ },
219
226
  generatedImportsFor(pack) {
220
227
  if (!Object.hasOwn(stagedPacks, pack)) {
221
228
  throw new Error(`Generated imports reference an unknown pack: ${pack}`);
@@ -242,6 +249,7 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
242
249
  const copy = Object.freeze({
243
250
  ...extension,
244
251
  ...(extension.packs ? { packs: Object.freeze([...extension.packs]) } : {}),
252
+ ...(extension.moduleNames ? { moduleNames: Object.freeze([...extension.moduleNames]) } : {}),
245
253
  ...(extension.inputs ? { inputs: Object.freeze([...extension.inputs]) } : {}),
246
254
  ...(extension.plugins ? { plugins: Object.freeze([...extension.plugins]) } : {}),
247
255
  ...(extension.resolveFromProject ? { resolveFromProject: Object.freeze([...extension.resolveFromProject]) } : {}),
@@ -252,6 +260,7 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
252
260
  allPacks: Object.freeze(stagedPacks),
253
261
  inspectPacks: currentPacks,
254
262
  outputPaths,
263
+ ...(apiOutput ? { apiOutput } : {}),
255
264
  profile,
256
265
  logger,
257
266
  signal,
@@ -280,6 +289,9 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
280
289
  }
281
290
  const importAs = options?.importAs;
282
291
  const pack = options?.pack;
292
+ if (options?.assetRegistry !== undefined && typeof options.assetRegistry !== 'boolean') {
293
+ throw new TypeError(`Artifact assetRegistry must be a boolean: ${id}`);
294
+ }
283
295
  if (pack !== undefined && !Object.hasOwn(stagedPacks, pack)) {
284
296
  throw new Error(`Artifact references an unknown pack: ${pack}`);
285
297
  }
@@ -301,7 +313,17 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
301
313
  generatedImports.set(importAs, id);
302
314
  }
303
315
  }
304
- artifacts.set(id, Object.freeze({ id, path: location, owner, ...(importAs ? { importAs } : {}), ...(pack ? { pack } : {}) }));
316
+ artifacts.set(id, Object.freeze({ id, path: location, owner, ...(importAs ? { importAs } : {}), ...(pack ? { pack } : {}), ...(options?.assetRegistry === false ? { assetRegistry: false } : {}) }));
317
+ },
318
+ finalizeArtifact(id, finalize) {
319
+ const artifact = artifacts.get(id);
320
+ if (!artifact || artifact.owner !== owner) {
321
+ throw new Error(`Artifact finalization requires an artifact owned by this invocation: ${id}`);
322
+ }
323
+ if (typeof finalize !== 'function' || artifactFinalizers.has(id)) {
324
+ throw new Error(`Artifact needs one finalizer function: ${id}`);
325
+ }
326
+ artifactFinalizers.set(id, finalize);
305
327
  },
306
328
  artifact(id) {
307
329
  const artifact = artifacts.get(id);
@@ -326,7 +348,6 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
326
348
  url.searchParams.set('build', path.basename(workspace));
327
349
  return loadPlugin(url.href, step.plugin);
328
350
  }
329
- await generateProject(context, metadata);
330
351
  for (const [index, step] of plan.entries()) {
331
352
  check(signal);
332
353
  owner = step.kind === 'plugin' ? `${step.plugin}:${index}` : step.stage;
@@ -366,7 +387,7 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
366
387
  logger.info?.(`@bedrock-core/builder: ${owner}`);
367
388
  }
368
389
  if (step.kind === 'plugin') {
369
- if (step.script === undefined) {
390
+ if (step.module !== undefined) {
370
391
  const plugin = await nativeImplementation(step);
371
392
  const invocations = nativePluginContexts(context, plugin, step, plugin.requirements === undefined ? [] : await currentPacks());
372
393
  const writes = sharedPackWrites(invocations, step.plugin);
@@ -407,10 +428,26 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
407
428
  }
408
429
  }
409
430
  }
431
+ await finalizePackManifests(stagedPacks);
432
+ for (const [id, finalize] of artifactFinalizers) {
433
+ check(signal);
434
+ await finalize(artifacts.get(id));
435
+ const file = await realpath(artifacts.get(id).path);
436
+ if (!inside(workspace, file) || !(await stat(file)).isFile()) {
437
+ throw new Error(`Invalid finalized artifact: ${id}`);
438
+ }
439
+ }
410
440
  await validatePackManifests(stagedPacks);
411
441
  await inspectPacks(stagedPacks);
442
+ const profileSettings = config.bedrockCore.profiles[profile];
443
+ const mode = profileSettings?.validation ?? 'warn';
444
+ const creatorTools = profileSettings?.creatorToolsValidation;
412
445
  validation = await validatePackContent({
413
446
  packs: await Promise.all(Object.keys(stagedPacks).map(id => context.inspectPack(id))),
447
+ mode,
448
+ projectRoot: project,
449
+ targetVersion: config.targetVersion,
450
+ creatorTools: creatorTools && creatorTools !== 'skip' ? { mode: creatorTools, projectRoot: project } : undefined,
414
451
  signal,
415
452
  async reuse(file, inputs, revision, validate) {
416
453
  const result = await cache.reuse(path.relative(staged, file).replaceAll('\\', '/'), {
@@ -423,22 +460,32 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
423
460
  return result.value;
424
461
  },
425
462
  });
426
- const checked = validation.files.filter(file => file.schema).length;
427
- logger.info?.(`@bedrock-core/builder: validated ${checked} content documents against Mojang schemas ${validation.schemaVersion}; ${validation.files.length - checked} additional JSON documents checked for syntax`);
428
- const schemaIssues = new Set(validation.files.flatMap(file => file.schemaIssue ? [file.schemaIssue] : []));
429
- for (const issue of schemaIssues) {
430
- logger.warn?.(`@bedrock-core/builder: ${issue}`);
463
+ const checked = validation.files.filter(file => file.category).length;
464
+ logger.info?.(validation.typesVersion
465
+ ? `@bedrock-core/builder: checked ${checked} content documents against Bedrock types ${validation.typesVersion}; ${validation.files.length - checked} additional JSON documents checked for syntax`
466
+ : `@bedrock-core/builder: checked ${validation.files.length} JSON documents for syntax`);
467
+ if (validation.typesIssue) {
468
+ logger.warn?.(`@bedrock-core/builder: ${validation.typesIssue}`);
469
+ }
470
+ const diagnostics = [...validation.files.flatMap(result => result.diagnostics), ...validation.creatorTools?.diagnostics ?? []];
471
+ for (const { pack, file, pointer, message } of diagnostics) {
472
+ logger.warn?.(`@bedrock-core/builder: ${pack}/${file}${pointer}: ${message}`);
431
473
  }
432
474
  }
433
475
  else if (step.stage === 'export') {
434
476
  publishedPacks = [...withDestinations(await inspectPacks(stagedPacks))];
435
- await inspect(staged, false);
477
+ await inspect(staged);
436
478
  check(signal);
437
- await publishNodeData(context, () => publish(stagedPacks, signal));
479
+ const apiPackage = artifacts.get('api:package');
480
+ await publishNodeData(context, () => publish(stagedPacks, signal, apiPackage ? path.dirname(apiPackage.path) : undefined));
438
481
  }
439
482
  else if (step.stage !== 'prepare') {
440
483
  const plugin = await implementation(step.stage);
441
484
  const outcome = await executePlugin(plugin, context, step.settings ?? {}, step.mode);
485
+ if (step.stage === 'manifest') {
486
+ const ui = config.bedrockCore.profiles[profile]?.stages?.['ui-compiler'];
487
+ await prepareAddonArtwork(context, typeof ui === 'object' ? ui : {});
488
+ }
442
489
  stageResults.push({ stage: step.stage, ...outcome });
443
490
  logger.info?.(`@bedrock-core/builder: ${step.stage} ${outcome.status}${outcome.reason ? ` (${outcome.reason})` : ''}`);
444
491
  }
@@ -455,11 +502,12 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
455
502
  const result = Object.freeze({
456
503
  validation: validation,
457
504
  outputPaths,
505
+ ...(artifacts.has('api:package') ? { apiOutput } : {}),
458
506
  profile,
459
507
  stages: stageResults,
460
508
  dependencies: [...dependencies],
461
509
  compilations: cache.results,
462
- artifacts: [...artifacts.values()].map(({ id, owner, importAs, pack }) => ({ id, owner, ...(importAs ? { importAs } : {}), ...(pack ? { pack } : {}) })),
510
+ artifacts: [...artifacts.values()].map(({ id, owner, importAs, pack, assetRegistry }) => ({ id, owner, ...(importAs ? { importAs } : {}), ...(pack ? { pack } : {}), ...(assetRegistry === false ? { assetRegistry } : {}) })),
463
511
  packs: publishedPacks.map(pack => ({ ...pack, path: outputPaths[pack.id] })),
464
512
  });
465
513
  trackLocations(result, dependencyLocations);
@@ -471,5 +519,5 @@ export async function runBuild({ configPath = 'config.json', profile = 'default'
471
519
  await rm(workspace, { recursive: true, force: true });
472
520
  }
473
521
  }
474
- });
522
+ }, apiOutput);
475
523
  }
@@ -2,3 +2,7 @@ import type { ProjectConfig } from './config.ts';
2
2
  /** Literal project paths omitted from staging and project watches. */
3
3
  export declare function stagingExclusions(project: string, config: ProjectConfig, configPath?: string): string[];
4
4
  export declare const isStagingExcluded: (file: string, exclusions: readonly string[]) => boolean;
5
+ /** A selected source or one of its ancestors needed to preserve project-relative paths. */
6
+ export declare const isStagingInput: (file: string, inputs: readonly string[]) => boolean;
7
+ /** Discover authored inputs without entering unrelated project directories or executing code. */
8
+ export declare function stagingInputs(project: string, config: ProjectConfig, profile?: string, configPath?: string, outputs?: readonly string[], signal?: AbortSignal): Promise<string[]>;