@playcraft/build 0.1.93-test → 0.1.95-test-a

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 (113) hide show
  1. package/dist/audio-source-files.d.ts +5 -0
  2. package/dist/audio-source-files.js +135 -0
  3. package/dist/base-builder.js +41 -2
  4. package/dist/delivery/agent-build-runner.d.ts +44 -0
  5. package/dist/delivery/agent-build-runner.js +365 -0
  6. package/dist/delivery/agent-build-source.d.ts +8 -0
  7. package/dist/delivery/agent-build-source.js +25 -0
  8. package/dist/delivery/artifact-descriptor.d.ts +31 -0
  9. package/dist/delivery/artifact-descriptor.js +237 -0
  10. package/dist/delivery/artifact-package.d.ts +43 -0
  11. package/dist/delivery/artifact-package.js +283 -0
  12. package/dist/delivery/build-plan.d.ts +4 -0
  13. package/dist/delivery/build-plan.js +189 -0
  14. package/dist/delivery/build-plan.types.d.ts +51 -0
  15. package/dist/delivery/build-plan.types.js +1 -0
  16. package/dist/delivery/command-isolation.d.ts +20 -0
  17. package/dist/delivery/command-isolation.js +324 -0
  18. package/dist/delivery/commands.d.ts +5 -0
  19. package/dist/delivery/commands.js +146 -0
  20. package/dist/delivery/files.d.ts +9 -0
  21. package/dist/delivery/files.js +144 -0
  22. package/dist/delivery/git-source-fingerprint.d.ts +2 -0
  23. package/dist/delivery/git-source-fingerprint.js +58 -0
  24. package/dist/delivery/isolated-source.d.ts +5 -0
  25. package/dist/delivery/isolated-source.js +126 -0
  26. package/dist/delivery/output-publication.d.ts +21 -0
  27. package/dist/delivery/output-publication.js +444 -0
  28. package/dist/delivery/project-delivery.d.ts +6 -0
  29. package/dist/delivery/project-delivery.js +287 -0
  30. package/dist/delivery/recipe-build-plan.d.ts +4 -0
  31. package/dist/delivery/recipe-build-plan.js +53 -0
  32. package/dist/delivery/recipe.d.ts +20 -0
  33. package/dist/delivery/recipe.js +211 -0
  34. package/dist/delivery/safe-path.d.ts +2 -0
  35. package/dist/delivery/safe-path.js +18 -0
  36. package/dist/delivery/types.d.ts +76 -0
  37. package/dist/delivery/types.js +1 -0
  38. package/dist/engines/engine-detector.js +4 -0
  39. package/dist/engines/generic-adapter.js +14 -19
  40. package/dist/index.d.ts +19 -4
  41. package/dist/index.js +11 -2
  42. package/dist/platforms/adikteev.js +1 -0
  43. package/dist/platforms/applovin.js +1 -0
  44. package/dist/platforms/base.js +2 -2
  45. package/dist/platforms/bigo.js +1 -0
  46. package/dist/platforms/facebook.js +1 -0
  47. package/dist/platforms/google.js +1 -0
  48. package/dist/platforms/inmobi.js +1 -0
  49. package/dist/platforms/ironsource.js +1 -0
  50. package/dist/platforms/liftoff.js +1 -0
  51. package/dist/platforms/mintegral.js +1 -0
  52. package/dist/platforms/moloco.js +1 -0
  53. package/dist/platforms/playcraft.js +1 -0
  54. package/dist/platforms/remerge.js +1 -0
  55. package/dist/platforms/snapchat.js +1 -0
  56. package/dist/platforms/tiktok.js +1 -0
  57. package/dist/platforms/unity.js +1 -0
  58. package/dist/production-animation-presence.d.ts +2 -0
  59. package/dist/production-animation-presence.js +146 -0
  60. package/dist/production-inputs.d.ts +30 -0
  61. package/dist/production-inputs.js +262 -0
  62. package/dist/production-source-paths.d.ts +5 -0
  63. package/dist/production-source-paths.js +27 -0
  64. package/dist/types.d.ts +5 -0
  65. package/dist/validation/artifact-qa.d.ts +44 -0
  66. package/dist/validation/artifact-qa.js +170 -0
  67. package/dist/validation/artifact-rules.d.ts +28 -0
  68. package/dist/validation/artifact-rules.js +440 -0
  69. package/dist/validation/artifact.d.ts +14 -0
  70. package/dist/validation/artifact.js +188 -0
  71. package/dist/validation/html-validator.d.ts +5 -0
  72. package/dist/validation/html-validator.js +19 -17
  73. package/dist/validation/index.d.ts +4 -0
  74. package/dist/validation/index.js +4 -0
  75. package/dist/validation/package-validator.d.ts +2 -0
  76. package/dist/validation/package-validator.js +25 -64
  77. package/dist/validation/profiles.d.ts +13 -1
  78. package/dist/validation/profiles.js +27 -0
  79. package/dist/validation/runtime-load.d.ts +89 -0
  80. package/dist/validation/runtime-load.js +654 -0
  81. package/dist/validation/source-scanner.d.ts +11 -0
  82. package/dist/validation/source-scanner.js +32 -2
  83. package/dist/validation/types.d.ts +155 -2
  84. package/dist/validation/types.js +1 -1
  85. package/dist/validation/validation-runner.d.ts +22 -2
  86. package/dist/validation/validation-runner.js +68 -3
  87. package/dist/validation/zip-reader.d.ts +7 -0
  88. package/dist/validation/zip-reader.js +159 -26
  89. package/dist/vite/config-builder-generic.d.ts +3 -1
  90. package/dist/vite/config-builder-generic.js +9 -7
  91. package/dist/vite/config-builder.js +1 -1
  92. package/dist/vite/plugin-platform.js +30 -54
  93. package/dist/vite/plugin-source-builder.d.ts +2 -14
  94. package/dist/vite/plugin-source-builder.js +61 -997
  95. package/dist/vite/source-builder-asset-paths.d.ts +25 -0
  96. package/dist/vite/source-builder-asset-paths.js +154 -0
  97. package/dist/vite/source-builder-esm.d.ts +7 -0
  98. package/dist/vite/source-builder-esm.js +877 -0
  99. package/dist/vite/source-builder-types.d.ts +14 -0
  100. package/dist/vite/source-builder-types.js +1 -0
  101. package/dist/vite/workspace.d.ts +6 -0
  102. package/dist/vite/workspace.js +41 -0
  103. package/dist/vite-builder.d.ts +4 -5
  104. package/dist/vite-builder.js +33 -34
  105. package/dist/workspace-css-imports.d.ts +2 -0
  106. package/dist/workspace-css-imports.js +139 -0
  107. package/dist/workspace-model-source.d.ts +14 -0
  108. package/dist/workspace-model-source.js +184 -0
  109. package/dist/workspace-public-imports.d.ts +11 -0
  110. package/dist/workspace-public-imports.js +232 -0
  111. package/dist/workspace-public-source.d.ts +15 -0
  112. package/dist/workspace-public-source.js +564 -0
  113. package/package.json +16 -4
@@ -0,0 +1,14 @@
1
+ import type { ImportMapAsset } from '../loaders/playcanvas-loader.js';
2
+ export interface SourceBuilderPluginOptions {
3
+ projectDir: string;
4
+ outputDir: string;
5
+ selectedScenes?: string[];
6
+ buildMode?: 'classic' | 'esm';
7
+ importMap?: ImportMapAsset;
8
+ }
9
+ export interface UserScript {
10
+ id: string;
11
+ path: string;
12
+ code: string;
13
+ name: string;
14
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ /** Trusted Runtime/Runner-only paths. Never expose these through BuildOptions or model input. */
2
+ export type ViteWorkspace = {
3
+ intermediateDir: string;
4
+ finalOutputDir: string;
5
+ };
6
+ export declare function resolveViteWorkspace(baseBuildDir: string, workspace: ViteWorkspace): ViteWorkspace;
@@ -0,0 +1,41 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ function inside(root, candidate) {
4
+ const relative = path.relative(root, candidate);
5
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
6
+ }
7
+ function canonicalDirectory(value, field) {
8
+ if (!path.isAbsolute(value))
9
+ throw new Error(`${field} must be an absolute Runtime workspace path`);
10
+ const requested = path.resolve(value);
11
+ const parent = path.dirname(requested);
12
+ const parentInfo = fs.lstatSync(parent);
13
+ if (!parentInfo.isDirectory() || parentInfo.isSymbolicLink()) {
14
+ throw new Error(`${field} must have a real parent directory`);
15
+ }
16
+ const canonical = path.join(fs.realpathSync.native(parent), path.basename(requested));
17
+ if (fs.existsSync(requested)) {
18
+ const info = fs.lstatSync(requested);
19
+ if (!info.isDirectory() || info.isSymbolicLink() || fs.realpathSync.native(requested) !== canonical) {
20
+ throw new Error(`${field} must be a real non-aliased directory`);
21
+ }
22
+ }
23
+ return canonical;
24
+ }
25
+ export function resolveViteWorkspace(baseBuildDir, workspace) {
26
+ const source = fs.realpathSync.native(baseBuildDir);
27
+ const requestedIntermediate = path.resolve(workspace.intermediateDir);
28
+ const requestedFinal = path.resolve(workspace.finalOutputDir);
29
+ if (inside(requestedIntermediate, requestedFinal) || inside(requestedFinal, requestedIntermediate)) {
30
+ throw new Error('Vite intermediate and final directories must not overlap');
31
+ }
32
+ const intermediateDir = canonicalDirectory(workspace.intermediateDir, 'intermediateDir');
33
+ const finalOutputDir = canonicalDirectory(workspace.finalOutputDir, 'finalOutputDir');
34
+ if (inside(source, intermediateDir) || inside(source, finalOutputDir)) {
35
+ throw new Error('Injected Vite workspace directories must be outside the source directory');
36
+ }
37
+ if (inside(intermediateDir, finalOutputDir) || inside(finalOutputDir, intermediateDir)) {
38
+ throw new Error('Vite intermediate and final directories must not overlap');
39
+ }
40
+ return { intermediateDir, finalOutputDir };
41
+ }
@@ -1,4 +1,5 @@
1
1
  import type { BuildOptions, SizeReport } from './types.js';
2
+ import type { ViteWorkspace } from './vite/workspace.js';
2
3
  export interface ViteBuildOutput {
3
4
  outputPath: string;
4
5
  size: number;
@@ -21,11 +22,13 @@ export interface ViteBuildOutput {
21
22
  * - 其他引擎:使用 GenericViteConfigBuilder(通用 HTML 内联 + 平台 SDK 注入)
22
23
  */
23
24
  export declare class ViteBuilder {
25
+ private workspace?;
24
26
  private baseBuildDir;
25
27
  private options;
26
28
  private sizeReport;
27
29
  private engine;
28
- constructor(baseBuildDir: string, options: BuildOptions);
30
+ private resolvedOutputDir?;
31
+ constructor(baseBuildDir: string, options: BuildOptions, workspace?: ViteWorkspace | undefined);
29
32
  /**
30
33
  * 执行构建
31
34
  */
@@ -71,10 +74,6 @@ export declare class ViteBuilder {
71
74
  * 计算 Base Build 目录的总大小
72
75
  */
73
76
  private calculateBaseBuildSize;
74
- /**
75
- * 生成报告
76
- */
77
- private generateReport;
78
77
  /**
79
78
  * 获取大小报告
80
79
  */
@@ -21,7 +21,8 @@ import { formatValidationSummary, hasBlockingValidationErrors, runPlayableValida
21
21
  * - 其他引擎:使用 GenericViteConfigBuilder(通用 HTML 内联 + 平台 SDK 注入)
22
22
  */
23
23
  export class ViteBuilder {
24
- constructor(baseBuildDir, options) {
24
+ constructor(baseBuildDir, options, workspace) {
25
+ this.workspace = workspace;
25
26
  this.engine = 'playcanvas';
26
27
  this.baseBuildDir = baseBuildDir;
27
28
  this.options = options;
@@ -39,19 +40,24 @@ export class ViteBuilder {
39
40
  async build() {
40
41
  // 1. 读取构建元数据获取引擎类型
41
42
  const metadata = await this.readBuildMetadata();
42
- this.engine = this.options.engine ?? metadata?.engine ?? 'playcanvas';
43
+ this.engine = metadata?.deliveryRecipeDigest
44
+ ? 'generic'
45
+ : (this.options.engine ?? metadata?.engine ?? 'playcanvas');
43
46
  console.log(`[ViteBuilder] 使用引擎: ${this.engine}`);
44
47
  // 2. 验证输入
45
48
  await this.validateBaseBuild(metadata);
46
49
  // 3. 根据引擎类型创建对应的配置构建器
47
50
  let configBuilder;
48
- if (this.engine === 'playcanvas') {
51
+ if (this.engine === 'playcanvas' && !metadata?.deliveryRecipeDigest) {
52
+ if (this.workspace) {
53
+ throw new Error('The legacy PlayCanvas packager does not support isolated Vite workspaces');
54
+ }
49
55
  console.log('[ViteBuilder] 使用 PlayCanvas 配置构建器');
50
56
  configBuilder = new ViteConfigBuilder(this.baseBuildDir, this.options.platform, this.options);
51
57
  }
52
58
  else {
53
59
  console.log('[ViteBuilder] 使用通用配置构建器(外部引擎)');
54
- configBuilder = new GenericViteConfigBuilder(this.baseBuildDir, this.options.platform, this.options, metadata);
60
+ configBuilder = new GenericViteConfigBuilder(this.baseBuildDir, this.options.platform, this.options, metadata, this.workspace);
55
61
  }
56
62
  const viteConfig = await configBuilder.create();
57
63
  // 4. 执行 Vite 构建
@@ -59,32 +65,34 @@ export class ViteBuilder {
59
65
  await viteBuild(viteConfig);
60
66
  }
61
67
  catch (error) {
68
+ const buildError = error;
62
69
  // 打印完整的 Vite/Rollup 错误信息,便于定位构建失败原因
63
70
  console.error('[ViteBuilder] Vite 构建失败:');
64
- if (error.id) {
65
- console.error(` - 问题文件: ${error.id}`);
71
+ if (buildError.id) {
72
+ console.error(` - 问题文件: ${buildError.id}`);
66
73
  }
67
- if (error.loc) {
68
- console.error(` - 位置: 行 ${error.loc.line}, 列 ${error.loc.column}`);
74
+ if (buildError.loc) {
75
+ console.error(` - 位置: 行 ${buildError.loc.line}, 列 ${buildError.loc.column}`);
69
76
  }
70
- if (error.frame) {
71
- console.error(` - 代码片段:\n${error.frame}`);
77
+ if (buildError.frame) {
78
+ console.error(` - 代码片段:\n${buildError.frame}`);
72
79
  }
73
- if (error.plugin) {
74
- console.error(` - 插件: ${error.plugin}`);
80
+ if (buildError.plugin) {
81
+ console.error(` - 插件: ${buildError.plugin}`);
75
82
  }
76
- if (error.pluginCode) {
77
- console.error(` - 插件错误码: ${error.pluginCode}`);
83
+ if (buildError.pluginCode) {
84
+ console.error(` - 插件错误码: ${buildError.pluginCode}`);
78
85
  }
79
- if (error.cause) {
80
- console.error(` - 原因:`, error.cause);
86
+ if (buildError.cause) {
87
+ console.error(` - 原因:`, buildError.cause);
81
88
  }
82
- console.error(` - 完整错误:`, error.stack || error.message || error);
89
+ console.error(` - 完整错误:`, buildError.stack || buildError.message || error);
83
90
  throw error;
84
91
  }
85
92
  // 5. 将输出从临时目录复制到最终目录
86
93
  const viteOutputDir = configBuilder.getViteOutputDir();
87
94
  const finalOutputDir = configBuilder.getFinalOutputDir();
95
+ this.resolvedOutputDir = finalOutputDir || undefined;
88
96
  if (viteOutputDir && finalOutputDir && viteOutputDir !== finalOutputDir) {
89
97
  await this.copyOutputToFinalDir(viteOutputDir, finalOutputDir);
90
98
  }
@@ -92,8 +100,6 @@ export class ViteBuilder {
92
100
  const outputPath = this.getOutputPath();
93
101
  await this.validateSize(outputPath);
94
102
  await this.runComplianceValidation(outputPath, metadata);
95
- // 7. 生成报告
96
- this.generateReport(outputPath);
97
103
  return outputPath;
98
104
  }
99
105
  /**
@@ -107,7 +113,7 @@ export class ViteBuilder {
107
113
  console.log(`[ViteBuilder] 读取构建元数据: engine=${metadata.engine}, mode=${metadata.mode}`);
108
114
  return metadata;
109
115
  }
110
- catch (error) {
116
+ catch {
111
117
  console.warn('[ViteBuilder] 无法读取构建元数据,假设为 PlayCanvas');
112
118
  return null;
113
119
  }
@@ -118,7 +124,7 @@ export class ViteBuilder {
118
124
  */
119
125
  async validateBaseBuild(metadata) {
120
126
  const engine = this.options.engine ?? metadata?.engine ?? 'playcanvas';
121
- if (engine === 'playcanvas') {
127
+ if (engine === 'playcanvas' && !metadata?.deliveryRecipeDigest) {
122
128
  await this.validatePlayCanvasBuild();
123
129
  }
124
130
  else {
@@ -254,7 +260,7 @@ export class ViteBuilder {
254
260
  */
255
261
  getOutputPath() {
256
262
  const platformConfig = PLATFORM_CONFIGS[this.options.platform];
257
- const outputDir = this.options.outputDir || './dist';
263
+ const outputDir = this.resolvedOutputDir ?? this.options.outputDir ?? './dist';
258
264
  // 使用用户指定的格式,如果没有则使用平台默认格式
259
265
  const outputFormat = this.options.format || platformConfig.outputFormat;
260
266
  if (outputFormat === 'zip') {
@@ -295,7 +301,7 @@ export class ViteBuilder {
295
301
  console.warn(`⚠️ ============================================================\n`);
296
302
  }
297
303
  }
298
- catch (error) {
304
+ catch {
299
305
  console.warn(`警告: 无法读取输出文件: ${outputPath}`);
300
306
  }
301
307
  }
@@ -336,13 +342,6 @@ export class ViteBuilder {
336
342
  }
337
343
  return totalSize;
338
344
  }
339
- /**
340
- * 生成报告
341
- */
342
- generateReport(outputPath) {
343
- // 报告已在 validateSize 中生成
344
- // 这里可以添加额外的报告逻辑
345
- }
346
345
  /**
347
346
  * 获取大小报告
348
347
  */
@@ -361,8 +360,8 @@ export class ViteBuilder {
361
360
  return;
362
361
  }
363
362
  const isZip = outputPath.toLowerCase().endsWith('.zip');
364
- const stages = validationOptions?.stages
365
- ?? (isZip ? ['delivery-package'] : ['html-artifact']);
363
+ const stages = validationOptions?.stages ??
364
+ (isZip ? ['delivery-package'] : ['html-artifact']);
366
365
  const report = await runPlayableValidation({
367
366
  projectRoot: this.baseBuildDir,
368
367
  channel: this.options.platform,
@@ -375,7 +374,7 @@ export class ViteBuilder {
375
374
  : 'generic',
376
375
  htmlPath: isZip ? undefined : outputPath,
377
376
  packagePath: isZip ? outputPath : undefined,
378
- outputDir: this.options.outputDir,
377
+ outputDir: this.resolvedOutputDir ?? this.options.outputDir,
379
378
  sourceGlobs: validationOptions?.sourceGlobs,
380
379
  metadata: metadata ? { ...metadata } : undefined,
381
380
  }, stages);
@@ -399,6 +398,6 @@ export class ViteBuilder {
399
398
  const k = 1024;
400
399
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
401
400
  const i = Math.floor(Math.log(bytes) / Math.log(k));
402
- return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
401
+ return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
403
402
  }
404
403
  }
@@ -0,0 +1,2 @@
1
+ /** Pure static extraction shared by save, frozen source and the self-contained delivery Runner. */
2
+ export declare function workspaceCssResourceSpecifiers(text: string, fail: () => never): string[];
@@ -0,0 +1,139 @@
1
+ import parse from 'css-tree/parser';
2
+ import walk from 'css-tree/walker';
3
+ import { tokenize, tokenTypes } from 'css-tree/tokenizer';
4
+ import { ident } from 'css-tree/utils';
5
+ const atRules = new Set([
6
+ 'charset', 'import', 'namespace', 'media', 'supports', 'container', 'layer',
7
+ 'font-face', 'font-feature-values', 'font-palette-values', 'keyframes', 'page',
8
+ 'counter-style', 'property', 'scope', 'starting-style', 'view-transition',
9
+ 'position-try', 'document', 'custom-media',
10
+ ]);
11
+ const scopedAtRules = new Map([
12
+ ['font-feature-values', new Set(['stylistic', 'styleset', 'character-variant', 'swash', 'ornaments', 'annotation'])],
13
+ ['page', new Set([
14
+ 'top-left-corner', 'top-left', 'top-center', 'top-right', 'top-right-corner',
15
+ 'bottom-left-corner', 'bottom-left', 'bottom-center', 'bottom-right', 'bottom-right-corner',
16
+ 'left-top', 'left-middle', 'left-bottom', 'right-top', 'right-middle', 'right-bottom',
17
+ ])],
18
+ ]);
19
+ const atRuleName = (name) => name.toLowerCase().replace(/^-(?:webkit|moz|ms|o)-/, '');
20
+ /** Validate actual CSS tokens before the parser can recover an unterminated string/block at EOF. */
21
+ function strictSource(text, fail) {
22
+ const closing = [];
23
+ const replacements = [];
24
+ let cursor = 0;
25
+ tokenize(text, (type, start, end) => {
26
+ const raw = text.slice(start, end);
27
+ const terminated = (character) => {
28
+ if (!raw.endsWith(character))
29
+ fail();
30
+ let escapes = 0;
31
+ for (let index = raw.length - 2; index >= 0 && raw[index] === '\\'; index--)
32
+ escapes++;
33
+ if (escapes % 2)
34
+ fail();
35
+ };
36
+ if (type === tokenTypes.BadString || type === tokenTypes.BadUrl)
37
+ fail();
38
+ if (type === tokenTypes.String)
39
+ terminated(raw[0]);
40
+ if (type === tokenTypes.Url)
41
+ terminated(')');
42
+ if (type === tokenTypes.Comment && !raw.endsWith('*/'))
43
+ fail();
44
+ if (type === tokenTypes.Function || type === tokenTypes.LeftParenthesis)
45
+ closing.push(tokenTypes.RightParenthesis);
46
+ else if (type === tokenTypes.LeftCurlyBracket)
47
+ closing.push(tokenTypes.RightCurlyBracket);
48
+ else if (type === tokenTypes.LeftSquareBracket)
49
+ closing.push(tokenTypes.RightSquareBracket);
50
+ else if ([tokenTypes.RightParenthesis, tokenTypes.RightCurlyBracket, tokenTypes.RightSquareBracket].includes(type) && closing.pop() !== type)
51
+ fail();
52
+ if (closing.length > 128)
53
+ fail();
54
+ if (type === tokenTypes.Function || type === tokenTypes.AtKeyword) {
55
+ const normalized = type === tokenTypes.Function ? `${ident.decode(raw.slice(0, -1))}(` : `@${ident.decode(raw.slice(1))}`;
56
+ if (normalized !== raw) {
57
+ replacements.push(text.slice(cursor, start), normalized);
58
+ cursor = end;
59
+ }
60
+ }
61
+ });
62
+ if (closing.length)
63
+ fail();
64
+ return replacements.length ? replacements.join('') + text.slice(cursor) : text;
65
+ }
66
+ /** Pure static extraction shared by save, frozen source and the self-contained delivery Runner. */
67
+ export function workspaceCssResourceSpecifiers(text, fail) {
68
+ const ast = parse(strictSource(text, fail), { parseCustomProperty: true, onParseError: fail });
69
+ const result = [];
70
+ const imageSet = (node, add) => {
71
+ let first = true;
72
+ const descriptors = new Set();
73
+ for (const child of node.children) {
74
+ if (child.type === 'Operator' && child.value === ',') {
75
+ if (first)
76
+ fail();
77
+ first = true;
78
+ descriptors.clear();
79
+ }
80
+ else if (first) {
81
+ if (child.type === 'String')
82
+ add(child.value);
83
+ else if (child.type !== 'Url' && !(child.type === 'Function' && /^(?:(?:repeating-)?(?:linear|radial|conic)-gradient|-webkit-image-set|image-set|cross-fade)$/i.test(child.name)))
84
+ fail();
85
+ first = false;
86
+ }
87
+ else if (child.type === 'Dimension' && /^(?:x|dpi|dpcm|dppx)$/i.test(ident.decode(child.unit)) && Number(child.value) >= 0) {
88
+ if (descriptors.has('resolution'))
89
+ fail();
90
+ descriptors.add('resolution');
91
+ }
92
+ else if (child.type === 'Function' && child.name.toLowerCase() === 'type' && child.children.size === 1 && child.children.first?.type === 'String') {
93
+ if (descriptors.has('type'))
94
+ fail();
95
+ descriptors.add('type');
96
+ }
97
+ else
98
+ fail();
99
+ }
100
+ if (first)
101
+ fail();
102
+ };
103
+ walk(ast, function (node) {
104
+ const add = (specifier) => {
105
+ // A relative custom-property URL is resolved at var()'s use site, which may
106
+ // belong to a different stylesheet; preserve the previous parser's refusal.
107
+ if (this.declaration?.property.startsWith('--') && !/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(specifier))
108
+ fail();
109
+ result.push(specifier);
110
+ };
111
+ if (node.type === 'Raw')
112
+ fail();
113
+ // Namespace identifiers and supports/media feature-test URLs do not fetch files.
114
+ if (node.type === 'Url' && (!this.atrulePrelude ||
115
+ this.atrule?.name.toLowerCase() === 'import' && this.atrulePrelude.children.first === node))
116
+ add(node.value);
117
+ if (node.type === 'Declaration' && !node.property.startsWith('--') && node.value.type === 'Value' && node.value.children.isEmpty)
118
+ fail();
119
+ if (node.type === 'Atrule' && !atRules.has(atRuleName(node.name)) &&
120
+ !scopedAtRules.get(atRuleName(this.atrule?.name ?? ''))?.has(node.name.toLowerCase()))
121
+ fail();
122
+ if (node.type === 'Atrule' && node.name.toLowerCase() === 'import') {
123
+ const first = node.prelude?.type === 'AtrulePrelude' ? node.prelude.children.first : undefined;
124
+ if (first?.type === 'String')
125
+ add(first.value);
126
+ else if (first?.type !== 'Url')
127
+ fail();
128
+ }
129
+ if (node.type === 'Function') {
130
+ const name = node.name.toLowerCase();
131
+ if (!this.atrulePrelude && ['image-set', '-webkit-image-set'].includes(name))
132
+ imageSet(node, add);
133
+ // These resource-bearing syntaxes need their own explicit static grammar.
134
+ if (['src', 'image', 'url'].includes(name))
135
+ fail();
136
+ }
137
+ });
138
+ return result;
139
+ }
@@ -0,0 +1,14 @@
1
+ type SourceFile = {
2
+ body: Buffer;
3
+ mode: '100644' | '100755';
4
+ };
5
+ /** Only the public parameter declaration can activate this model-specific hidden closure. */
6
+ export declare function readWorkspaceModelSourceClosure(input: {
7
+ dataPath: string | undefined;
8
+ workspaceProjection?: Buffer;
9
+ readFile: (path: string, maximum?: number) => Promise<SourceFile>;
10
+ }): Promise<{
11
+ files: Map<string, SourceFile>;
12
+ requiredPaths: string[];
13
+ }>;
14
+ export {};
@@ -0,0 +1,184 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { canonicalModelAdaptation, modelProductionRecipeSchema, workspaceAssetProvenanceDocumentSchema, workspaceModelAdaptationLineageSchema, workspaceModelAdaptationSchema, workspaceModelBuildInputsSchema, workspaceModelPreparationSourceLineageSchema, workspaceModelPreparationSourceToolSchema, workspaceRelativePathSchema, } from '@playcraft/common/cloud-workspace/runtime';
3
+ const DATA = '.playcraft/model-adaptation.json';
4
+ const LINEAGE = '.playcraft/model-adaptation-lineage.json';
5
+ const BUILD = '.playcraft/model-build-inputs.json';
6
+ const PROVENANCE = '.playcraft/asset-provenance.json';
7
+ const WORKSPACE = '.playcraft/workspace.json';
8
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
9
+ const same = (left, right) => canonicalModelAdaptation(left) === canonicalModelAdaptation(right);
10
+ /** Only the public parameter declaration can activate this model-specific hidden closure. */
11
+ export async function readWorkspaceModelSourceClosure(input) {
12
+ const files = new Map(), required = new Set();
13
+ if (input.dataPath !== DATA)
14
+ return { files, requiredPaths: [] };
15
+ let bytesRead = 0;
16
+ function fail(code, path) {
17
+ throw new Error(`${code}: ${path}`);
18
+ }
19
+ const ordinary = (path) => {
20
+ if (!workspaceRelativePathSchema.safeParse(path).success ||
21
+ path.split('/').some((part) => part.toLowerCase() === '.playcraft'))
22
+ fail('workspace_public_model_path_unsupported', path);
23
+ };
24
+ const read = async (path, expected, maximum = 64 * 1024 * 1024) => {
25
+ let file = files.get(path);
26
+ if (!file) {
27
+ file = await input.readFile(path, maximum);
28
+ bytesRead += file.body.length;
29
+ if (file.body.length > maximum || files.size >= 512 || bytesRead > 256 * 1024 * 1024)
30
+ fail('workspace_public_model_input_limit', path);
31
+ files.set(path, file);
32
+ }
33
+ if (file.body.length > maximum)
34
+ fail('workspace_public_model_input_limit', path);
35
+ required.add(path);
36
+ if (expected !== undefined && hash(file.body) !== expected)
37
+ fail('workspace_public_model_input_changed', path);
38
+ return file;
39
+ };
40
+ const optional = async (path, maximum) => {
41
+ try {
42
+ return await read(path, undefined, maximum);
43
+ }
44
+ catch (error) {
45
+ if (error.code === 'ENOENT')
46
+ return undefined;
47
+ throw error;
48
+ }
49
+ };
50
+ const parse = (path, file, parser) => {
51
+ try {
52
+ return parser.parse(JSON.parse(file.body.toString('utf8')));
53
+ }
54
+ catch {
55
+ return fail('workspace_public_model_declaration_invalid', path);
56
+ }
57
+ };
58
+ const plan = parse(DATA, await read(DATA, undefined, 1024 * 1024), workspaceModelAdaptationSchema);
59
+ const lineage = parse(LINEAGE, await read(LINEAGE, undefined, 1024 * 1024), workspaceModelAdaptationLineageSchema);
60
+ if (!same(plan.source, lineage.derivedSource))
61
+ fail('workspace_public_model_source_changed', DATA);
62
+ // derivedPlanHash records creation, not the current editable scalar parameters.
63
+ const parentPath = '.playcraft/parent-model-adaptation.json';
64
+ const parent = parse(parentPath, await read(parentPath, lineage.parentPlanHash, 1024 * 1024), workspaceModelAdaptationSchema);
65
+ if (!same(parent.source, lineage.parentSource) ||
66
+ !same(plan.source, {
67
+ ...parent.source,
68
+ path: `source/${parent.source.path}`,
69
+ files: parent.source.files.map((file) => ({ ...file, path: `source/${file.path}` })),
70
+ }))
71
+ fail('workspace_public_model_source_changed', LINEAGE);
72
+ for (const file of plan.source.files) {
73
+ ordinary(file.path);
74
+ await read(file.path, file.contentHash);
75
+ }
76
+ await read('src/assets/packed-model.glb', lineage.packedHash);
77
+ await read('src/runtime/model-adaptation-core.js', lineage.coreHash);
78
+ const rawBuild = lineage.buildBindingVersion === 2
79
+ ? await read(BUILD, undefined, 512 * 1024)
80
+ : await optional(BUILD, 512 * 1024);
81
+ const declaration = rawBuild && parse(BUILD, rawBuild, workspaceModelBuildInputsSchema);
82
+ if (declaration &&
83
+ (declaration.models.length !== 1 || !same(declaration.models[0].source, plan.source)))
84
+ fail('workspace_public_model_source_changed', BUILD);
85
+ const adaptationFiles = declaration?.models[0].adaptationFiles ?? [];
86
+ const declared = new Map(adaptationFiles.map((file) => [file.path, file]));
87
+ const proofRoots = new Set();
88
+ for (const file of adaptationFiles) {
89
+ if (!file.path.startsWith('.playcraft/model-production/'))
90
+ continue;
91
+ const match = /^\.playcraft\/model-production\/([a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12})\//i.exec(file.path);
92
+ if (!match || !file.contentHash)
93
+ fail('workspace_public_model_path_unsupported', file.path);
94
+ proofRoots.add(`.playcraft/model-production/${match[1]}`);
95
+ }
96
+ const allowedProofs = new Map();
97
+ for (const prefix of proofRoots) {
98
+ const path = `${prefix}/lineage.json`, entry = declared.get(path);
99
+ if (!entry?.contentHash)
100
+ fail('workspace_public_model_lineage_missing', path);
101
+ const proof = parse(path, await read(path, entry.contentHash, 4 * 1024 * 1024), workspaceModelPreparationSourceLineageSchema);
102
+ if (prefix !== `.playcraft/model-production/${proof.pipelineId}` ||
103
+ !same(proof.outputSource, plan.source) ||
104
+ !same(proof.actualInspection.plan.source, proof.actualInspection.source) ||
105
+ !same(proof.outputSource, {
106
+ ...proof.actualInspection.source,
107
+ path: `source/${proof.actualInspection.source.path}`,
108
+ files: proof.actualInspection.source.files.map((file) => ({
109
+ ...file,
110
+ path: `source/${file.path}`,
111
+ })),
112
+ }))
113
+ fail('workspace_public_model_source_changed', path);
114
+ const names = [
115
+ 'lineage.json',
116
+ 'recipe.json',
117
+ 'tool.json',
118
+ 'inspect-model.glb',
119
+ 'inspect-source-inspection.json',
120
+ ];
121
+ if (proof.recipe.repair)
122
+ names.push('repair-model.glb', 'repair-repair-manifest.json');
123
+ if (proof.recipe.split)
124
+ names.push('split-model.glb', 'split-split-manifest.json', 'split-exterior-trace.json');
125
+ if (proof.recipe.optimize)
126
+ names.push('optimize-model.glb', 'optimize-optimization.json');
127
+ for (const original of proof.parentSource.files) {
128
+ ordinary(original.path);
129
+ names.push(`original/${original.path}`);
130
+ const originalEntry = declared.get(`${prefix}/original/${original.path}`);
131
+ if (originalEntry?.contentHash !== original.contentHash)
132
+ fail('workspace_public_model_input_changed', `${prefix}/original/${original.path}`);
133
+ }
134
+ for (const name of names) {
135
+ const path = `${prefix}/${name}`, expected = declared.get(path)?.contentHash;
136
+ if (!expected)
137
+ fail('workspace_public_model_lineage_missing', path);
138
+ allowedProofs.set(path, expected);
139
+ }
140
+ const recipePath = `${prefix}/recipe.json`;
141
+ const recipe = parse(recipePath, await read(recipePath, allowedProofs.get(recipePath), 1024 * 1024), modelProductionRecipeSchema);
142
+ if (!same(recipe, proof.recipe))
143
+ fail('workspace_public_model_input_changed', recipePath);
144
+ const toolPath = `${prefix}/tool.json`;
145
+ const tool = parse(toolPath, await read(toolPath, allowedProofs.get(toolPath), 4 * 1024 * 1024), workspaceModelPreparationSourceToolSchema);
146
+ if (tool.toolHash !== proof.toolHash ||
147
+ !same(tool.actualInspector, proof.actualInspection.tool) ||
148
+ (tool.manifest &&
149
+ (tool.manifest.toolHash !== tool.toolHash ||
150
+ hash(canonicalModelAdaptation(tool.manifest.files)) !== tool.toolHash)))
151
+ fail('workspace_public_model_input_changed', toolPath);
152
+ }
153
+ const fixed = new Set([DATA, LINEAGE, PROVENANCE, WORKSPACE, parentPath]);
154
+ for (const file of adaptationFiles) {
155
+ if (file.path.split('/').some((part) => part.toLowerCase() === '.playcraft') &&
156
+ !fixed.has(file.path) &&
157
+ !allowedProofs.has(file.path))
158
+ fail('workspace_public_model_path_unsupported', file.path);
159
+ if (!file.path.startsWith('.playcraft/'))
160
+ ordinary(file.path);
161
+ const observed = await read(file.path, file.contentHash);
162
+ if (file.path === WORKSPACE &&
163
+ file.contentHash &&
164
+ (!input.workspaceProjection ||
165
+ hash(input.workspaceProjection) !== file.contentHash ||
166
+ hash(observed.body) !== file.contentHash))
167
+ fail('workspace_public_model_projection_unsupported', file.path);
168
+ }
169
+ const provenanceRaw = await optional(PROVENANCE, 16 * 1024 * 1024);
170
+ if (provenanceRaw) {
171
+ const provenance = parse(PROVENANCE, provenanceRaw, workspaceAssetProvenanceDocumentSchema);
172
+ for (const asset of provenance.assets) {
173
+ ordinary(asset.path);
174
+ await read(asset.path, asset.provenance.modelSha256);
175
+ if (asset.licensePath !== `licenses/assets/${hash(asset.provenance.licenseText)}.txt`)
176
+ fail('workspace_public_model_license_changed', asset.licensePath);
177
+ if (!(await read(asset.licensePath, undefined, 64 * 1024)).body.equals(Buffer.from(asset.provenance.licenseText)))
178
+ fail('workspace_public_model_license_changed', asset.licensePath);
179
+ }
180
+ }
181
+ // The caller owns the canonical public projection; raw private workspace bytes never escape here.
182
+ files.delete(WORKSPACE);
183
+ return { files, requiredPaths: [...required].sort() };
184
+ }
@@ -0,0 +1,11 @@
1
+ export type PublicSourceDependency = {
2
+ specifier: string;
3
+ kind: 'module' | 'resource' | 'types';
4
+ };
5
+ export declare class WorkspacePublicSourceError extends Error {
6
+ readonly code: string;
7
+ readonly file?: string | undefined;
8
+ constructor(code: string, file?: string | undefined);
9
+ }
10
+ /** Static syntax only. No project config, plugin, module or package code is executed. */
11
+ export declare function workspacePublicSourceDependencies(path: string, body: Buffer): PublicSourceDependency[];