@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,440 @@
1
+ import path from 'node:path';
2
+ import { formatBytes } from '../utils.js';
3
+ import { collectExternalResources, collectLocalResourceReferences, isAllowedExternalResource, } from './html-validator.js';
4
+ import { getChannelRuleProfile } from './profiles.js';
5
+ import { ranStageReport } from './validation-runner.js';
6
+ /**
7
+ * `base-output` rules: channel-independent checks that read the built artifact only. They do not
8
+ * depend on the engine or the build tool that produced the artifact.
9
+ */
10
+ export const BASE_OUTPUT_RULE_IDS = {
11
+ entryParsable: 'common.artifact.entry.parsable',
12
+ sizeBudget: 'common.artifact.size.budget',
13
+ localReference: 'common.artifact.local-reference.resolvable',
14
+ externalResource: 'common.artifact.external-resource.forbidden',
15
+ devAddress: 'common.artifact.dev-address.forbidden',
16
+ inlineData: 'common.artifact.inline-data.valid',
17
+ sizeBreakdown: 'common.artifact.size.breakdown',
18
+ debugResidue: 'common.artifact.debug-residue.review',
19
+ directRedirect: 'common.artifact.redirect.direct.review',
20
+ persistentStorage: 'common.artifact.storage.persistent.review',
21
+ viewportMeta: 'common.artifact.viewport-meta.present',
22
+ };
23
+ /** Reference limit when no finite limit is given: most channels cap creatives at 5 MB. */
24
+ const DEFAULT_SIZE_LIMIT = 5 * 1024 * 1024;
25
+ /** `base` stage: static checks of the artifact files. Needs only the artifact. */
26
+ export async function runBaseStage(artifact, options = {}) {
27
+ const startedAt = Date.now();
28
+ const sizeLimitBytes = options.sizeLimitBytes !== undefined && Number.isFinite(options.sizeLimitBytes)
29
+ ? options.sizeLimitBytes
30
+ : DEFAULT_SIZE_LIMIT;
31
+ const externalCheck = getChannelRuleProfile(options.profile ?? 'playcraft').rules.find((rule) => rule.stage === 'html-artifact' && rule.check?.kind === 'external-resources')?.check;
32
+ const allowedExternalPatterns = externalCheck?.kind === 'external-resources' ? externalCheck.allowedPatterns : undefined;
33
+ const results = await runBaseOutputChecks(artifact, {
34
+ sizeLimitBytes,
35
+ ...(allowedExternalPatterns ? { allowedExternalPatterns } : {}),
36
+ });
37
+ return ranStageReport('base', startedAt, results, { details: { sizeLimitBytes } });
38
+ }
39
+ const RULES = {
40
+ [BASE_OUTPUT_RULE_IDS.entryParsable]: {
41
+ title: 'Entry HTML is valid UTF-8 and contains HTML markup',
42
+ severity: 'error',
43
+ recommendation: 'Make the build write a UTF-8 HTML entry file.',
44
+ confidence: 'high',
45
+ },
46
+ [BASE_OUTPUT_RULE_IDS.sizeBudget]: {
47
+ title: 'Artifact stays within the size limit',
48
+ severity: 'error',
49
+ recommendation: 'Compress images and audio, remove unused assets, or enable image compression when exporting. The final channel package size decides delivery.',
50
+ confidence: 'medium',
51
+ },
52
+ [BASE_OUTPUT_RULE_IDS.localReference]: {
53
+ title: 'Every local file the artifact references is inside the artifact',
54
+ severity: 'error',
55
+ recommendation: 'Inline the referenced file, or include it in the build output at the referenced path.',
56
+ confidence: 'high',
57
+ },
58
+ [BASE_OUTPUT_RULE_IDS.externalResource]: {
59
+ title: 'Artifact does not load remote scripts, styles, images, fonts or media',
60
+ severity: 'error',
61
+ recommendation: 'Bundle or inline the resource; a playable must run without network access except for channel SDKs the channel provides.',
62
+ confidence: 'high',
63
+ },
64
+ [BASE_OUTPUT_RULE_IDS.devAddress]: {
65
+ title: 'Artifact contains no local development addresses or machine paths',
66
+ severity: 'error',
67
+ recommendation: 'Build in production mode and remove references to localhost, the dev server or absolute local paths.',
68
+ confidence: 'medium',
69
+ },
70
+ [BASE_OUTPUT_RULE_IDS.inlineData]: {
71
+ title: 'Inline base64 data decodes and matches its declared type',
72
+ severity: 'error',
73
+ recommendation: 'Re-encode the asset, or fix the declared MIME type of the data URI.',
74
+ confidence: 'high',
75
+ },
76
+ [BASE_OUTPUT_RULE_IDS.sizeBreakdown]: {
77
+ title: 'Size breakdown by asset type',
78
+ severity: 'info',
79
+ recommendation: 'Start size reductions with the largest categories and items.',
80
+ confidence: 'high',
81
+ },
82
+ [BASE_OUTPUT_RULE_IDS.debugResidue]: {
83
+ title: 'Artifact contains no source maps or debugging tools',
84
+ severity: 'warning',
85
+ recommendation: 'Disable source maps in the production build and remove debug panels, consoles and debugger statements.',
86
+ confidence: 'medium',
87
+ },
88
+ [BASE_OUTPUT_RULE_IDS.directRedirect]: {
89
+ title: 'Artifact does not redirect directly',
90
+ severity: 'warning',
91
+ recommendation: 'Open the store through the ad SDK CTA (sdk.install()) after a user tap instead of window.open or location.',
92
+ confidence: 'medium',
93
+ },
94
+ [BASE_OUTPUT_RULE_IDS.viewportMeta]: {
95
+ title: 'Entry HTML declares a mobile viewport',
96
+ severity: 'error',
97
+ recommendation: 'Add <meta name="viewport" content="width=device-width, initial-scale=1"> to the entry HTML head; without it mobile browsers lay the page out at desktop width.',
98
+ confidence: 'high',
99
+ },
100
+ [BASE_OUTPUT_RULE_IDS.persistentStorage]: {
101
+ title: 'Artifact does not depend on persistent browser storage',
102
+ severity: 'warning',
103
+ recommendation: 'Ad containers may block storage; keep state in memory, or make storage access optional and guarded.',
104
+ confidence: 'low',
105
+ },
106
+ };
107
+ const TEXT_FILE = /\.(?:html?|m?js|css|json|svg|txt)$/i;
108
+ const MARKUP_FILE = /\.(?:html?|css)$/i;
109
+ const INJECTED_SCRIPT = /<script\b[^>]*\bdata-playcraft-injected\b[^>]*>[\s\S]*?<\/script>/gi;
110
+ const DATA_URI = /data:([a-z]+\/[a-z0-9.+-]+)((?:;[a-z0-9-]+=[^;,"'\s)]+)*);base64,([A-Za-z0-9+/]+={0,2})/gi;
111
+ const MAX_DATA_URIS = 2000;
112
+ const MAX_EVIDENCE = 10;
113
+ const DEV_ADDRESS_PATTERNS = [
114
+ /\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d+)?/gi,
115
+ /\/@vite\/client\b/g,
116
+ /\/@react-refresh\b/g,
117
+ /\bfile:\/\/\//gi,
118
+ /["'`](?:\/Users\/|\/home\/)[^"'`\s]+/g,
119
+ /["'`][A-Za-z]:\\\\(?:Users|Documents and Settings)\\\\[^"'`\s]+/g,
120
+ ];
121
+ const SOURCE_MAP = /(?:\/\/|\/\*)[#@]\s*sourceMappingURL=(?!data:)[^\s'"<>*]+/g;
122
+ const DEBUG_TOOLS = /\b(?:lil-gui|dat\.gui|vConsole|VConsole|eruda)\b|\bdebugger\s*;/g;
123
+ const DIRECT_REDIRECT = /\bwindow\s*\.\s*open\s*\(|\blocation\s*\.\s*(?:assign|replace)\s*\(|\blocation(?:\s*\.\s*href)?\s*=(?!=)/g;
124
+ const PERSISTENT_STORAGE = /\b(?:localStorage|sessionStorage|indexedDB)\b/g;
125
+ const INLINE_CATEGORIES = new Set(['image', 'audio', 'video', 'font']);
126
+ const CATEGORY_BY_EXTENSION = {
127
+ png: 'image',
128
+ jpg: 'image',
129
+ jpeg: 'image',
130
+ gif: 'image',
131
+ webp: 'image',
132
+ avif: 'image',
133
+ svg: 'image',
134
+ mp3: 'audio',
135
+ ogg: 'audio',
136
+ wav: 'audio',
137
+ m4a: 'audio',
138
+ aac: 'audio',
139
+ mp4: 'video',
140
+ webm: 'video',
141
+ woff: 'font',
142
+ woff2: 'font',
143
+ ttf: 'font',
144
+ otf: 'font',
145
+ glb: 'model',
146
+ gltf: 'model',
147
+ bin: 'model',
148
+ js: 'code',
149
+ mjs: 'code',
150
+ css: 'code',
151
+ html: 'code',
152
+ htm: 'code',
153
+ json: 'code',
154
+ };
155
+ async function runBaseOutputChecks(artifact, options) {
156
+ const results = [];
157
+ const entryResult = await checkEntryParsable(artifact);
158
+ results.push(entryResult);
159
+ if (entryResult.status === 'fail')
160
+ return results;
161
+ const textFiles = await readTextFiles(artifact);
162
+ results.push(checkViewportMeta(artifact.entry, textFiles));
163
+ results.push(checkSizeBudget(artifact, options));
164
+ results.push(checkLocalReferences(artifact, textFiles));
165
+ results.push(checkExternalResources(textFiles, options.allowedExternalPatterns));
166
+ results.push(patternResult(BASE_OUTPUT_RULE_IDS.devAddress, textFiles, DEV_ADDRESS_PATTERNS, artifact.entry));
167
+ results.push(checkInlineData(textFiles, artifact.entry));
168
+ results.push(sizeBreakdown(artifact, textFiles));
169
+ results.push(checkDebugResidue(artifact, textFiles));
170
+ results.push(patternResult(BASE_OUTPUT_RULE_IDS.directRedirect, textFiles, [DIRECT_REDIRECT], artifact.entry));
171
+ results.push(patternResult(BASE_OUTPUT_RULE_IDS.persistentStorage, textFiles, [PERSISTENT_STORAGE], artifact.entry));
172
+ return results;
173
+ }
174
+ async function checkEntryParsable(artifact) {
175
+ const id = BASE_OUTPUT_RULE_IDS.entryParsable;
176
+ const buffer = await artifact.readBuffer(artifact.entry);
177
+ if (!buffer)
178
+ return result(id, false, { file: artifact.entry, evidence: 'entry is not readable' });
179
+ let content;
180
+ try {
181
+ content = new TextDecoder('utf-8', { fatal: true }).decode(buffer);
182
+ }
183
+ catch {
184
+ return result(id, false, { file: artifact.entry, evidence: 'entry is not valid UTF-8' });
185
+ }
186
+ const markup = /<(?:html|head|body|script|canvas)\b/i.test(content);
187
+ return result(id, markup, {
188
+ file: artifact.entry,
189
+ ...(markup ? {} : { evidence: 'no <html>, <head>, <body>, <script> or <canvas> tag found' }),
190
+ });
191
+ }
192
+ function checkViewportMeta(entry, textFiles) {
193
+ const html = textFiles.find((file) => file.path === entry)?.scan ?? '';
194
+ const tag = Array.from(html.matchAll(/<meta\b[^>]*>/gi))
195
+ .map((match) => match[0])
196
+ .find((item) => /\bname\s*=\s*["']?viewport\b/i.test(item));
197
+ const content = tag?.match(/\bcontent\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
198
+ const value = content?.[1] ?? content?.[2] ?? '';
199
+ const ok = /\bwidth\s*=\s*device-width\b/i.test(value);
200
+ return result(BASE_OUTPUT_RULE_IDS.viewportMeta, ok, {
201
+ file: entry,
202
+ evidence: tag ? `found ${tag.slice(0, 200)}` : 'no <meta name="viewport"> tag',
203
+ });
204
+ }
205
+ function checkSizeBudget(artifact, options) {
206
+ const limit = options.sizeLimitBytes;
207
+ const size = artifact.totalSize;
208
+ const margin = limit - size;
209
+ const evidence = `size=${formatBytes(size)}, limit=${formatBytes(limit)}, margin=${margin >= 0 ? formatBytes(margin) : `-${formatBytes(-margin)}`}`;
210
+ if (size > limit)
211
+ return result(BASE_OUTPUT_RULE_IDS.sizeBudget, false, { evidence });
212
+ if (margin < limit * 0.1)
213
+ return result(BASE_OUTPUT_RULE_IDS.sizeBudget, false, {
214
+ evidence: `${evidence}; less than 10% of the limit remains`,
215
+ status: 'warning',
216
+ });
217
+ return result(BASE_OUTPUT_RULE_IDS.sizeBudget, true, { evidence });
218
+ }
219
+ function checkLocalReferences(artifact, textFiles) {
220
+ const paths = new Set(artifact.files.map((file) => file.path));
221
+ const missing = [];
222
+ for (const file of textFiles.filter((item) => MARKUP_FILE.test(item.path))) {
223
+ for (const reference of collectLocalResourceReferences(file.scan)) {
224
+ const target = resolveReference(file.path, reference);
225
+ if (target === undefined || !paths.has(target))
226
+ missing.push(`${file.path} → ${reference}`);
227
+ }
228
+ }
229
+ return result(BASE_OUTPUT_RULE_IDS.localReference, missing.length === 0, {
230
+ file: artifact.entry,
231
+ ...(missing.length > 0 ? { evidence: summarizeList(missing) } : {}),
232
+ });
233
+ }
234
+ function resolveReference(fromFile, reference) {
235
+ const withoutQuery = reference.split(/[?#]/, 1)[0] ?? '';
236
+ if (!withoutQuery)
237
+ return fromFile;
238
+ let decoded;
239
+ try {
240
+ decoded = decodeURIComponent(withoutQuery);
241
+ }
242
+ catch {
243
+ decoded = withoutQuery;
244
+ }
245
+ const joined = decoded.startsWith('/')
246
+ ? decoded.slice(1)
247
+ : path.posix.join(path.posix.dirname(fromFile), decoded);
248
+ const normalized = path.posix.normalize(joined);
249
+ return normalized.startsWith('../') || normalized === '..' ? undefined : normalized;
250
+ }
251
+ function checkExternalResources(textFiles, allowedPatterns) {
252
+ const external = [];
253
+ for (const file of textFiles.filter((item) => MARKUP_FILE.test(item.path))) {
254
+ for (const url of collectExternalResources(file.scan)) {
255
+ if (!isAllowedExternalResource(url, allowedPatterns))
256
+ external.push(`${file.path} → ${url}`);
257
+ }
258
+ }
259
+ return result(BASE_OUTPUT_RULE_IDS.externalResource, external.length === 0, {
260
+ ...(external.length > 0 ? { evidence: summarizeList(external) } : {}),
261
+ });
262
+ }
263
+ function checkInlineData(textFiles, entry) {
264
+ const problems = [];
265
+ let checked = 0;
266
+ let firstFile;
267
+ for (const file of textFiles) {
268
+ for (const match of file.scan.matchAll(DATA_URI)) {
269
+ if (checked >= MAX_DATA_URIS)
270
+ break;
271
+ checked += 1;
272
+ const mime = match[1].toLowerCase();
273
+ const payload = match[3];
274
+ const problem = inlineDataProblem(mime, payload);
275
+ if (problem) {
276
+ firstFile ?? (firstFile = file.path);
277
+ problems.push(`${file.path}:${lineOf(file.content, match.index ?? 0)} ${mime} ${problem}`);
278
+ }
279
+ }
280
+ }
281
+ return result(BASE_OUTPUT_RULE_IDS.inlineData, problems.length === 0, {
282
+ file: firstFile ?? entry,
283
+ evidence: problems.length > 0 ? summarizeList(problems) : `checked ${checked} inline data URI(s)`,
284
+ });
285
+ }
286
+ function inlineDataProblem(mime, payload) {
287
+ if (payload.length % 4 === 1)
288
+ return 'has a truncated base64 payload';
289
+ const bytes = Buffer.from(payload, 'base64');
290
+ if (bytes.length === 0)
291
+ return 'is empty';
292
+ const signature = SIGNATURES_BY_MIME.get(mime);
293
+ if (!signature || signature(bytes))
294
+ return undefined;
295
+ return `does not start with a ${mime} signature`;
296
+ }
297
+ const startsWith = (...values) => (bytes) => values.every((value, index) => bytes[index] === value);
298
+ const ascii = (offset, text) => (bytes) => bytes.subarray(offset, offset + text.length).toString('latin1') === text;
299
+ const all = (...signatures) => (bytes) => signatures.every((signature) => signature(bytes));
300
+ const any = (...signatures) => (bytes) => signatures.some((signature) => signature(bytes));
301
+ const mpegFrame = (bytes) => bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xe0) === 0xe0;
302
+ /** Leading bytes of each MIME type checked; other types are not checked. */
303
+ const SIGNATURES = [
304
+ [['image/png'], startsWith(0x89, 0x50, 0x4e, 0x47)],
305
+ [['image/jpeg', 'image/jpg'], startsWith(0xff, 0xd8, 0xff)],
306
+ [['image/gif'], ascii(0, 'GIF8')],
307
+ [['image/webp'], all(ascii(0, 'RIFF'), ascii(8, 'WEBP'))],
308
+ [['audio/mpeg', 'audio/mp3'], any(ascii(0, 'ID3'), mpegFrame)],
309
+ [['audio/ogg', 'video/ogg'], ascii(0, 'OggS')],
310
+ [['audio/wav', 'audio/wave', 'audio/x-wav'], all(ascii(0, 'RIFF'), ascii(8, 'WAVE'))],
311
+ [['audio/mp4', 'audio/aac', 'video/mp4'], any(ascii(4, 'ftyp'), startsWith(0xff, 0xf1))],
312
+ [['font/woff', 'application/font-woff'], ascii(0, 'wOFF')],
313
+ [['font/woff2'], ascii(0, 'wOF2')],
314
+ [
315
+ ['font/ttf', 'font/sfnt', 'application/x-font-ttf'],
316
+ any(startsWith(0x00, 0x01, 0x00, 0x00), ascii(0, 'true')),
317
+ ],
318
+ [['font/otf'], ascii(0, 'OTTO')],
319
+ ];
320
+ const SIGNATURES_BY_MIME = new Map(SIGNATURES.flatMap(([mimes, signature]) => mimes.map((mime) => [mime, signature])));
321
+ function sizeBreakdown(artifact, textFiles) {
322
+ const categories = new Map();
323
+ const items = [];
324
+ const add = (category, bytes) => categories.set(category, (categories.get(category) ?? 0) + bytes);
325
+ const textByPath = new Map(textFiles.map((file) => [file.path, file]));
326
+ for (const file of artifact.files) {
327
+ const text = textByPath.get(file.path);
328
+ let inlineBytes = 0;
329
+ if (text) {
330
+ let index = 0;
331
+ for (const match of text.content.matchAll(DATA_URI)) {
332
+ const bytes = match[0].length;
333
+ inlineBytes += bytes;
334
+ index += 1;
335
+ const kind = match[1].toLowerCase().split('/')[0];
336
+ add(INLINE_CATEGORIES.has(kind) ? kind : 'other', bytes);
337
+ items.push({ label: `${file.path} inline ${match[1]} #${index}`, bytes });
338
+ }
339
+ }
340
+ const extension = path.posix.extname(file.path).slice(1).toLowerCase();
341
+ const remaining = Math.max(0, file.size - inlineBytes);
342
+ add(CATEGORY_BY_EXTENSION[extension] ?? 'other', remaining);
343
+ items.push({ label: file.path, bytes: remaining });
344
+ }
345
+ const total = [...categories.values()].reduce((sum, bytes) => sum + bytes, 0) || 1;
346
+ const byCategory = [...categories.entries()]
347
+ .filter(([, bytes]) => bytes > 0)
348
+ .sort((a, b) => b[1] - a[1])
349
+ .map(([category, bytes]) => `${category}=${formatBytes(bytes)} (${Math.round((bytes / total) * 100)}%)`)
350
+ .join(', ');
351
+ const largest = items
352
+ .filter((item) => item.bytes > 0)
353
+ .sort((a, b) => b.bytes - a.bytes)
354
+ .slice(0, 5)
355
+ .map((item) => `${item.label} ${formatBytes(item.bytes)}`)
356
+ .join('; ');
357
+ return result(BASE_OUTPUT_RULE_IDS.sizeBreakdown, true, {
358
+ evidence: `${byCategory}. Largest: ${largest}`,
359
+ });
360
+ }
361
+ function checkDebugResidue(artifact, textFiles) {
362
+ const findings = collectMatches(textFiles, [SOURCE_MAP, DEBUG_TOOLS]);
363
+ for (const file of artifact.files)
364
+ if (file.path.endsWith('.map'))
365
+ findings.unshift({ file: file.path, line: 1, text: 'source map file' });
366
+ return findingsResult(BASE_OUTPUT_RULE_IDS.debugResidue, findings, artifact.entry);
367
+ }
368
+ function patternResult(id, textFiles, patterns, entry) {
369
+ return findingsResult(id, collectMatches(textFiles, patterns), entry);
370
+ }
371
+ function collectMatches(textFiles, patterns) {
372
+ const findings = [];
373
+ for (const file of textFiles) {
374
+ for (const pattern of patterns) {
375
+ for (const match of file.scan.matchAll(new RegExp(pattern.source, pattern.flags))) {
376
+ findings.push({
377
+ file: file.path,
378
+ line: lineOf(file.content, match.index ?? 0),
379
+ text: match[0].slice(0, 120),
380
+ });
381
+ if (findings.length >= 50)
382
+ return findings;
383
+ }
384
+ }
385
+ }
386
+ return findings;
387
+ }
388
+ function findingsResult(id, findings, entry) {
389
+ const first = findings[0];
390
+ return result(id, findings.length === 0, {
391
+ file: first?.file ?? entry,
392
+ ...(first ? { line: first.line } : {}),
393
+ ...(findings.length > 0
394
+ ? { evidence: summarizeList(findings.map((item) => `${item.file}:${item.line} ${item.text}`)) }
395
+ : {}),
396
+ });
397
+ }
398
+ async function readTextFiles(artifact) {
399
+ const files = [];
400
+ for (const file of artifact.files.filter((item) => TEXT_FILE.test(item.path))) {
401
+ const content = await artifact.readText(file.path);
402
+ if (content === null)
403
+ continue;
404
+ files.push({ path: file.path, content, scan: maskInjectedScripts(content) });
405
+ }
406
+ return files;
407
+ }
408
+ /** Blanks scripts the platform injected at build time, keeping line numbers intact. */
409
+ function maskInjectedScripts(content) {
410
+ return content.replace(INJECTED_SCRIPT, (match) => match.replace(/[^\n]/g, ' '));
411
+ }
412
+ function lineOf(content, index) {
413
+ let line = 1;
414
+ for (let position = 0; position < index; position += 1)
415
+ if (content.charCodeAt(position) === 10)
416
+ line += 1;
417
+ return line;
418
+ }
419
+ function summarizeList(items) {
420
+ const shown = items.slice(0, MAX_EVIDENCE).join('; ');
421
+ return items.length > MAX_EVIDENCE ? `${shown}; … ${items.length - MAX_EVIDENCE} more` : shown;
422
+ }
423
+ function result(id, passed, details) {
424
+ const rule = RULES[id];
425
+ const status = details.status ?? (passed ? 'pass' : rule.severity === 'error' ? 'fail' : 'warning');
426
+ return {
427
+ ruleId: id,
428
+ channel: 'common',
429
+ stage: 'base-output',
430
+ severity: rule.severity,
431
+ status,
432
+ message: passed ? `${rule.title}: passed` : rule.title,
433
+ recommendation: rule.recommendation,
434
+ ...(details.file ? { file: details.file } : {}),
435
+ ...(details.line ? { line: details.line } : {}),
436
+ ...(details.evidence ? { evidence: details.evidence } : {}),
437
+ owner: 'playcraft-build',
438
+ confidence: rule.confidence,
439
+ };
440
+ }
@@ -0,0 +1,14 @@
1
+ import { type ZipEntryInfo } from './zip-reader.js';
2
+ import type { ArtifactReadErrorCode, PlayableArtifact, ReadArtifactOptions } from './types.js';
3
+ export declare class ArtifactReadError extends Error {
4
+ readonly code: ArtifactReadErrorCode;
5
+ constructor(code: ArtifactReadErrorCode, message: string);
6
+ }
7
+ /**
8
+ * Reads a built playable from a single HTML file, a ZIP file or a directory, and resolves its
9
+ * entry HTML. Only the artifact is inspected; how it was built does not matter.
10
+ */
11
+ export declare function readArtifact(inputPath: string, options?: ReadArtifactOptions): Promise<PlayableArtifact>;
12
+ /** Lists a directory like a ZIP central directory: files and `/`-terminated directories. */
13
+ export declare function listDirectoryEntries(dir: string): Promise<ZipEntryInfo[]>;
14
+ export declare function directorySize(dir: string): Promise<number>;
@@ -0,0 +1,188 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { SimpleZipReader } from './zip-reader.js';
5
+ export class ArtifactReadError extends Error {
6
+ constructor(code, message) {
7
+ super(message);
8
+ this.code = code;
9
+ this.name = 'ArtifactReadError';
10
+ }
11
+ }
12
+ const HTML_FILE = /\.html?$/i;
13
+ /**
14
+ * Reads a built playable from a single HTML file, a ZIP file or a directory, and resolves its
15
+ * entry HTML. Only the artifact is inspected; how it was built does not matter.
16
+ */
17
+ export async function readArtifact(inputPath, options = {}) {
18
+ const sourcePath = path.resolve(inputPath);
19
+ const stat = await fs.stat(sourcePath).catch(() => undefined);
20
+ if (!stat)
21
+ throw new ArtifactReadError('artifact_not_found', `Artifact not found: ${sourcePath}`);
22
+ if (stat.isDirectory()) {
23
+ const source = await directorySource(sourcePath);
24
+ return artifact(sourcePath, 'directory', source, resolveEntry(source.files, options.entry));
25
+ }
26
+ const buffer = await fs.readFile(sourcePath);
27
+ if (isZip(buffer)) {
28
+ const source = zipSource(buffer);
29
+ return artifact(sourcePath, 'zip', source, resolveEntry(source.files, options.entry));
30
+ }
31
+ if (HTML_FILE.test(sourcePath)) {
32
+ if (options.entry !== undefined)
33
+ throw new ArtifactReadError('artifact_entry_invalid', 'An entry can only be chosen inside a ZIP file or a directory');
34
+ const name = path.basename(sourcePath);
35
+ const source = {
36
+ files: [{ path: name, size: buffer.length }],
37
+ totalSize: buffer.length,
38
+ read: async (filePath) => (filePath === name ? buffer : null),
39
+ };
40
+ return artifact(sourcePath, 'html', source, name);
41
+ }
42
+ throw new ArtifactReadError('artifact_unsupported', `Unsupported artifact: ${sourcePath} (expected an HTML file, a ZIP file or a directory)`);
43
+ }
44
+ async function artifact(sourcePath, container, source, entry) {
45
+ const read = async (filePath) => {
46
+ const normalized = normalizeInnerPath(filePath);
47
+ return normalized === undefined ? null : source.read(normalized);
48
+ };
49
+ return {
50
+ sourcePath,
51
+ container,
52
+ layout: source.files.length === 1 ? 'single-html' : 'multi-file',
53
+ entry,
54
+ files: source.files,
55
+ totalSize: source.totalSize,
56
+ digest: await contentDigest(source),
57
+ readBuffer: read,
58
+ readText: async (filePath) => (await read(filePath))?.toString('utf-8') ?? null,
59
+ };
60
+ }
61
+ function resolveEntry(files, requested) {
62
+ const paths = new Set(files.map((file) => file.path));
63
+ if (requested !== undefined) {
64
+ const entry = normalizeInnerPath(requested);
65
+ if (entry === undefined || !HTML_FILE.test(entry))
66
+ throw new ArtifactReadError('artifact_entry_invalid', `Entry must be an HTML file inside the artifact: ${requested}`);
67
+ if (!paths.has(entry))
68
+ throw new ArtifactReadError('artifact_entry_missing', `Entry not found in artifact: ${entry}`);
69
+ return entry;
70
+ }
71
+ if (paths.has('index.html'))
72
+ return 'index.html';
73
+ const html = files.filter((file) => HTML_FILE.test(file.path)).map((file) => file.path);
74
+ if (html.length === 1)
75
+ return html[0];
76
+ if (html.length === 0)
77
+ throw new ArtifactReadError('artifact_entry_missing', 'The artifact contains no HTML entry');
78
+ throw new ArtifactReadError('artifact_entry_ambiguous', `The artifact has no index.html and several HTML files; choose one as the entry: ${html.slice(0, 10).join(', ')}`);
79
+ }
80
+ /** `/`-separated path inside the artifact, or undefined when it is absolute or leaves the artifact. */
81
+ function normalizeInnerPath(filePath) {
82
+ const value = filePath.replace(/\\/g, '/');
83
+ if (value.startsWith('/') || /^[a-zA-Z]:/.test(value))
84
+ return undefined;
85
+ const normalized = path.posix.normalize(value);
86
+ if (normalized === '..' || normalized.startsWith('../'))
87
+ return undefined;
88
+ return normalized.replace(/^\.\//, '');
89
+ }
90
+ function isZip(buffer) {
91
+ if (buffer.length < 4 || buffer[0] !== 0x50 || buffer[1] !== 0x4b)
92
+ return false;
93
+ const signature = buffer.readUInt32LE(0);
94
+ return signature === 0x04034b50 || signature === 0x06054b50;
95
+ }
96
+ function zipSource(buffer) {
97
+ const zip = new SimpleZipReader(buffer);
98
+ let entries;
99
+ try {
100
+ entries = zip.listEntries();
101
+ }
102
+ catch (error) {
103
+ throw new ArtifactReadError('artifact_zip_invalid', error instanceof Error ? error.message : String(error));
104
+ }
105
+ return {
106
+ files: entries
107
+ .filter((entry) => !entry.isDirectory)
108
+ .map((entry) => ({ path: entry.path, size: entry.uncompressedSize })),
109
+ totalSize: buffer.length,
110
+ read: async (filePath) => {
111
+ try {
112
+ return zip.readEntry(filePath);
113
+ }
114
+ catch (error) {
115
+ throw new ArtifactReadError('artifact_zip_invalid', error instanceof Error ? error.message : String(error));
116
+ }
117
+ },
118
+ };
119
+ }
120
+ async function directorySource(dir) {
121
+ const files = (await listDirectoryEntries(dir))
122
+ .filter((entry) => !entry.isDirectory)
123
+ .map((entry) => ({ path: entry.path, size: entry.uncompressedSize }));
124
+ return {
125
+ files,
126
+ totalSize: files.reduce((sum, file) => sum + file.size, 0),
127
+ read: async (filePath) => fs.readFile(path.join(dir, filePath)).catch(() => null),
128
+ };
129
+ }
130
+ /** Hashes each file's path and content, so the same files give the same digest in any container. */
131
+ async function contentDigest(source) {
132
+ const digest = createHash('sha256');
133
+ for (const file of [...source.files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {
134
+ const content = (await source.read(file.path)) ?? Buffer.alloc(0);
135
+ digest.update(file.path).update('\0').update(createHash('sha256').update(content).digest('hex')).update('\n');
136
+ }
137
+ return `sha256:${digest.digest('hex')}`;
138
+ }
139
+ /** Lists a directory like a ZIP central directory: files and `/`-terminated directories. */
140
+ export async function listDirectoryEntries(dir) {
141
+ const entries = [];
142
+ const walk = async (current) => {
143
+ const dirEntries = await fs.readdir(current, { withFileTypes: true });
144
+ for (const entry of dirEntries) {
145
+ const fullPath = path.join(current, entry.name);
146
+ const relative = path.relative(dir, fullPath).replace(/\\/g, '/');
147
+ if (entry.isDirectory()) {
148
+ entries.push({
149
+ path: `${relative}/`,
150
+ compressedSize: 0,
151
+ uncompressedSize: 0,
152
+ compressionMethod: 0,
153
+ isDirectory: true,
154
+ });
155
+ await walk(fullPath);
156
+ }
157
+ else {
158
+ const stat = await fs.stat(fullPath);
159
+ entries.push({
160
+ path: relative,
161
+ compressedSize: stat.size,
162
+ uncompressedSize: stat.size,
163
+ compressionMethod: 0,
164
+ isDirectory: false,
165
+ });
166
+ }
167
+ }
168
+ };
169
+ await walk(dir);
170
+ return entries;
171
+ }
172
+ export async function directorySize(dir) {
173
+ let total = 0;
174
+ const walk = async (current) => {
175
+ const entries = await fs.readdir(current, { withFileTypes: true });
176
+ for (const entry of entries) {
177
+ const fullPath = path.join(current, entry.name);
178
+ if (entry.isDirectory()) {
179
+ await walk(fullPath);
180
+ }
181
+ else {
182
+ total += (await fs.stat(fullPath)).size;
183
+ }
184
+ }
185
+ };
186
+ await walk(dir);
187
+ return total;
188
+ }
@@ -1,2 +1,7 @@
1
1
  import type { ChannelRuleProfile, ValidationContext, ValidationResult } from './types.js';
2
2
  export declare function validateHtmlArtifact(context: ValidationContext, profile?: ChannelRuleProfile): Promise<ValidationResult[]>;
3
+ /** Validates the exact final bytes, including objects downloaded by Business. */
4
+ export declare function validateHtmlArtifactContent(context: ValidationContext, content: string | Uint8Array, displayPath?: string, profile?: ChannelRuleProfile): ValidationResult[];
5
+ export declare function collectExternalResources(html: string): string[];
6
+ export declare function collectLocalResourceReferences(html: string): string[];
7
+ export declare function isAllowedExternalResource(url: string, allowedPatterns?: string[]): boolean;