@bedrock-core/builder-validation 0.2.0 → 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.
@@ -0,0 +1,187 @@
1
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
16
+ env.stack.push({ value: value, dispose: dispose, async: async });
17
+ }
18
+ else if (async) {
19
+ env.stack.push({ async: true });
20
+ }
21
+ return value;
22
+ };
23
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
24
+ return function (env) {
25
+ function fail(e) {
26
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
27
+ env.hasError = true;
28
+ }
29
+ var r, s = 0;
30
+ function next() {
31
+ while (r = env.stack.pop()) {
32
+ try {
33
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
34
+ if (r.dispose) {
35
+ var result = r.dispose.call(r.value);
36
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
37
+ }
38
+ else s |= 1;
39
+ }
40
+ catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
45
+ if (env.hasError) throw env.error;
46
+ }
47
+ return next();
48
+ };
49
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
50
+ var e = new Error(message);
51
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
52
+ });
53
+ import path from 'node:path';
54
+ import { ScriptKind, ScriptTarget, isInterfaceDeclaration, isPropertySignatureDeclaration, isStringLiteral } from 'typescript-native/ast';
55
+ import { computeLineStarts } from 'typescript-native/ast/scanner';
56
+ import { createFileSystemLayer } from 'typescript-native/fs';
57
+ import { ModuleKind, ModuleResolutionKind } from 'typescript-native/sync';
58
+ const exactCategories = {
59
+ 'bp/functions/tick.json': 'bp/functions/tick',
60
+ 'bp/item_catalog/crafting_item_catalog.json': 'bp/item_catalog/crafting_item_catalog',
61
+ 'bp/sounds/server_sound_definitions.json': 'bp/sounds/server_sound_definitions',
62
+ 'rp/blocks.json': 'rp/textures/blocks_resource',
63
+ 'rp/sounds.json': 'rp/sounds/events',
64
+ 'rp/sounds/sound_definitions.json': 'rp/sounds',
65
+ 'rp/sounds/music_definitions.json': 'rp/sounds/music_definitions',
66
+ 'rp/textures/terrain_texture.json': 'rp/textures/terrain_texture',
67
+ 'rp/textures/item_texture.json': 'rp/textures/item_texture',
68
+ 'rp/textures/texture_list.json': 'rp/textures/texture_list',
69
+ 'rp/textures/flipbook_textures.json': 'rp/textures/flipbook_textures',
70
+ };
71
+ const deferred = new Set(['lighting', 'color_grading', 'atmospherics', 'pbr', 'point_lights', 'shadows', 'water']);
72
+ export function documentCategory(kind, file) {
73
+ const [folder, section] = file.split('/', 2);
74
+ const prefix = kind === 'behavior' ? 'bp' : 'rp';
75
+ if (kind === 'behavior' && folder === 'shapes') {
76
+ return 'bp/voxel_shapes';
77
+ }
78
+ if (kind === 'behavior' && (folder === 'cameras' || folder === 'worldgen')) {
79
+ return 'bp/' + folder + '/' + section;
80
+ }
81
+ if (kind === 'resource' && file.endsWith('.texture_set.json')) {
82
+ return 'rp/textures/texture_set';
83
+ }
84
+ if (kind === 'resource' && deferred.has(folder)) {
85
+ return 'rp/deferred_rendering/' + folder;
86
+ }
87
+ return exactCategories[prefix + '/' + file] ?? prefix + '/' + folder;
88
+ }
89
+ export function declaredCategories(api, file) {
90
+ const env_1 = { stack: [], error: void 0, hasError: false };
91
+ try {
92
+ const declaration = __addDisposableResource(env_1, api.createSourceFileFromFile(file, { scriptKind: ScriptKind.TS }), false);
93
+ const map = declaration.sourceFile.statements.find(node => isInterfaceDeclaration(node) && node.name.text === 'DocumentTypes');
94
+ if (!map || !isInterfaceDeclaration(map)) {
95
+ throw new Error('Missing public DocumentTypes declarations in ' + file);
96
+ }
97
+ return new Set(map.members.flatMap(member => isPropertySignatureDeclaration(member) && isStringLiteral(member.name) ? [member.name.text] : []));
98
+ }
99
+ catch (e_1) {
100
+ env_1.error = e_1;
101
+ env_1.hasError = true;
102
+ }
103
+ finally {
104
+ __disposeResources(env_1);
105
+ }
106
+ }
107
+ export function documentLiteral(value) {
108
+ // Native diagnostics include source lines. Indentation keeps large documents from repeating in each diagnostic.
109
+ return JSON.stringify(value, null, 2).replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029');
110
+ }
111
+ function diagnosticMessage(diagnostic, depth = 0) {
112
+ return diagnostic.text + (diagnostic.messageChain ?? []).map(child => '\n' + ' '.repeat(depth + 1) + diagnosticMessage(child, depth + 1)).join('');
113
+ }
114
+ /** Type-check fresh JSON literals without executing their contents. */
115
+ export function createDocumentChecker(api, distribution, { additionalRoots = [], documentTypes } = {}) {
116
+ const compilerOptions = {
117
+ strict: true,
118
+ noEmit: true,
119
+ module: ModuleKind.NodeNext,
120
+ moduleResolution: ModuleResolutionKind.NodeNext,
121
+ target: ScriptTarget.ES2023,
122
+ types: [],
123
+ skipLibCheck: additionalRoots.length === 0,
124
+ };
125
+ const file = path.join(distribution, 'bedrock-document-check.cts');
126
+ const rootFiles = [file, ...additionalRoots];
127
+ const declarations = documentTypes !== undefined
128
+ ? [[path.join(distribution, 'audit-documents.d.ts'), documentTypes]]
129
+ : [];
130
+ const typeModule = declarations.length ? './audit-documents' : './documents';
131
+ return (pending, signal) => {
132
+ const findings = pending.map(() => []);
133
+ let start = 0;
134
+ while (start < pending.length) {
135
+ const env_2 = { stack: [], error: void 0, hasError: false };
136
+ try {
137
+ signal?.throwIfAborted();
138
+ const statements = [`import type { DocumentTypes } from '${typeModule}';\n`];
139
+ const ranges = [];
140
+ const offset = start;
141
+ let size = statements[0].length;
142
+ while (start < pending.length && ranges.length < 256 && size < 2 * 1024 * 1024) {
143
+ const { category, literal } = pending[start];
144
+ const prefix = `export const document${start}: DocumentTypes[${JSON.stringify(category)}] = `;
145
+ const statement = prefix + literal + ';\n';
146
+ ranges.push({ start: size, literalStart: size + prefix.length });
147
+ statements.push(statement);
148
+ size += statement.length;
149
+ start++;
150
+ }
151
+ const source = statements.join('');
152
+ const lineStarts = computeLineStarts(source);
153
+ const snapshot = __addDisposableResource(env_2, api.createSnapshot({
154
+ fileSystem: createFileSystemLayer([[file, source], ...declarations]),
155
+ createPrograms: [{ rootFiles, compilerOptions }],
156
+ }), false);
157
+ const program = __addDisposableResource(env_2, snapshot.operation.createdPrograms[0], false);
158
+ const diagnostics = [
159
+ ...program.getProgramDiagnostics(),
160
+ ...program.getGlobalDiagnostics(),
161
+ ...program.getSyntacticDiagnostics(),
162
+ ...program.getSemanticDiagnostics(),
163
+ ];
164
+ for (const diagnostic of diagnostics) {
165
+ const { code, fileName, startPosition } = diagnostic;
166
+ const message = diagnosticMessage(diagnostic);
167
+ const position = startPosition && fileName && path.normalize(fileName) === file
168
+ ? lineStarts[startPosition.line] + startPosition.character
169
+ : -1;
170
+ const index = ranges.findLastIndex(range => range.start <= position);
171
+ if (index < 0) {
172
+ throw new Error(`Declaration TS${code} in ${fileName ?? 'compiler'}: ${message}`);
173
+ }
174
+ findings[offset + index].push({ code, message, offset: position - ranges[index].literalStart });
175
+ }
176
+ }
177
+ catch (e_2) {
178
+ env_2.error = e_2;
179
+ env_2.hasError = true;
180
+ }
181
+ finally {
182
+ __disposeResources(env_2);
183
+ }
184
+ }
185
+ return findings;
186
+ };
187
+ }
@@ -1,70 +1,73 @@
1
+ import { type CreatorToolsResult, type CreatorToolsValidationOptions } from './creator-tools.ts';
2
+ import type { TypeSelection } from './types-release.ts';
3
+ export type { CreatorToolsDiagnostic, CreatorToolsResult, CreatorToolsValidationOptions } from './creator-tools.ts';
1
4
  /** Manifest-classified pack directory whose final JSON files are checked. */
2
5
  export interface ContentPack {
3
6
  /** Configured pack ID used in diagnostics. */
4
7
  id: string;
5
8
  /** Pack directory to inspect. */
6
9
  path: string;
7
- /** Manifest classification used to select applicable document schemas. */
10
+ /** Manifest classification used to select applicable document types. */
8
11
  kind: 'behavior' | 'resource' | 'other';
9
12
  }
10
13
  /** Validation failure located by pack, file and JSON pointer. */
11
14
  export interface ContentDiagnostic {
12
- /** Whether the parser or a content schema reported the problem. */
13
- kind?: 'syntax' | 'schema';
15
+ /** Validator that reported the problem. */
16
+ kind?: 'syntax' | 'type' | 'creator-tools';
14
17
  /** Configured pack ID. */
15
18
  pack: string;
16
19
  /** JSON file path relative to the pack directory, using forward slashes. */
17
20
  file: string;
18
21
  /** JSON pointer identifying the invalid value. */
19
22
  pointer: string;
20
- /** Syntax or schema validation explanation. */
23
+ /** Validation explanation. */
21
24
  message: string;
25
+ /** TypeScript diagnostic code for document type errors. */
26
+ code?: number;
22
27
  }
23
- /** Per-file syntax/schema diagnostics and any unavailable-schema explanation. */
28
+ /** Per-file syntax and document type diagnostics. */
24
29
  export interface ContentFileResult {
25
30
  /** Configured pack ID. */
26
31
  pack: string;
27
32
  /** Checked JSON path relative to the pack directory, using forward slashes. */
28
33
  file: string;
29
- /** Applied schema URL when a matching catalog schema is available. */
30
- schema?: string;
31
- /** Reason a matching upstream schema could not be applied. */
32
- schemaIssue?: string;
33
- /** Syntax and schema errors for this file. */
34
+ /** Applied DocumentTypes category when a matching type is available. */
35
+ category?: string;
36
+ /** Syntax and type errors for this file. */
34
37
  diagnostics: ContentDiagnostic[];
35
38
  }
36
- /** Schema catalog version and validation coverage for all checked files. */
39
+ /** Bedrock types release and validation coverage for the checked files. */
37
40
  export interface ContentValidationResult {
38
- /** Resolved Mojang schema catalog version, or an empty string when schema checks are skipped. */
39
- schemaVersion: string;
40
- /** Per-file checks and schema coverage. */
41
+ /** Resolved native types package version, or an empty string when type checking is unavailable or skipped. */
42
+ typesVersion: string;
43
+ /** Reason the types for this target could not be loaded. */
44
+ typesIssue?: string;
45
+ /** Per-file checks and type coverage. */
41
46
  files: ContentFileResult[];
47
+ /** Mojang CLI checks when Creator Tools is enabled. */
48
+ creatorTools?: CreatorToolsResult;
42
49
  }
43
- /** How to handle schema checks. Invalid JSON syntax always fails. */
50
+ /** How to handle document type checks. Invalid JSON syntax always fails. */
44
51
  export type ContentValidationMode = 'strict' | 'warn' | 'skip';
45
- /** Pack selection, schema catalog and optional validation-reuse integration. */
46
- export interface ContentValidationOptions {
52
+ /** Pack selection, installed native types and optional validation reuse. */
53
+ export interface ContentValidationOptions extends TypeSelection {
47
54
  /** Final pack directories to validate. */
48
55
  packs: readonly ContentPack[];
49
- /** Schema validation mode, defaulting to warn. */
56
+ /** Document type validation mode, defaulting to warn. */
50
57
  mode?: ContentValidationMode;
51
- /** Custom installed Mojang schema catalog directory. */
52
- schemaRoot?: string;
58
+ /** Optional Creator Tools checks on the complete pack set. */
59
+ creatorTools?: CreatorToolsValidationOptions;
53
60
  /** Cooperative validation cancellation. */
54
61
  signal?: AbortSignal;
55
- /** Reuse hook keyed by file, schema dependencies and validator revision; call validate on a miss. */
62
+ /** Reuse hook keyed by file, declaration dependencies and validator revision. Call validate on a miss. */
56
63
  reuse?: (file: string, dependencies: readonly string[], revision: string, validate: () => Promise<ContentFileResult>) => Promise<ContentFileResult>;
57
64
  }
58
- /** Aggregated JSON validation failure with structured diagnostics. */
65
+ /** Aggregated pack content failure with structured diagnostics. */
59
66
  export declare class ContentValidationError extends Error {
60
67
  /** Structured validation failures collected across checked files. */
61
68
  readonly diagnostics: readonly ContentDiagnostic[];
62
69
  /** Format the supplied structured diagnostics as one validation error. */
63
70
  constructor(diagnostics: ContentDiagnostic[]);
64
71
  }
65
- /**
66
- * Validate JSON syntax and apply content schemas according to the selected mode.
67
- * @param options Project inputs, settings and optional integrations for this operation.
68
- * @returns Per-file coverage and diagnostics. Syntax errors and strict schema errors throw ContentValidationError.
69
- */
72
+ /** Check final pack JSON syntax and the native document types for its Bedrock target. */
70
73
  export declare function validatePackContent(options: ContentValidationOptions): Promise<ContentValidationResult>;