@kubohiroya/sb3-toolchain 0.10.0 → 0.12.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.
- package/CHANGELOG.md +22 -0
- package/README.ja.md +17 -1
- package/README.md +17 -1
- package/dist/archive.d.ts +1 -0
- package/dist/archive.js +16 -0
- package/dist/archive.js.map +1 -0
- package/dist/assert.d.ts +2 -0
- package/dist/assert.js +11 -0
- package/dist/assert.js.map +1 -0
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +12 -0
- package/dist/bin.js.map +1 -0
- package/dist/build.d.ts +23 -0
- package/dist/build.js +111 -0
- package/dist/build.js.map +1 -0
- package/dist/cli.d.ts +87 -0
- package/dist/cli.js +544 -0
- package/dist/cli.js.map +1 -0
- package/dist/constants.d.ts +2 -0
- package/dist/constants.js +7 -0
- package/dist/constants.js.map +1 -0
- package/dist/extension-api-manifest.d.ts +46 -0
- package/dist/extension-api-manifest.js +211 -0
- package/dist/extension-api-manifest.js.map +1 -0
- package/dist/extension-bundle-archive.d.ts +36 -0
- package/dist/extension-bundle-archive.js +302 -0
- package/dist/extension-bundle-archive.js.map +1 -0
- package/dist/extension-bundle-configuration.d.ts +55 -0
- package/dist/extension-bundle-configuration.js +200 -0
- package/dist/extension-bundle-configuration.js.map +1 -0
- package/dist/extension-bundle.d.ts +39 -0
- package/dist/extension-bundle.js +580 -0
- package/dist/extension-bundle.js.map +1 -0
- package/dist/extension-dependencies.d.ts +18 -0
- package/dist/extension-dependencies.js +59 -0
- package/dist/extension-dependencies.js.map +1 -0
- package/dist/extension-id-migration.d.ts +83 -0
- package/dist/extension-id-migration.js +292 -0
- package/dist/extension-id-migration.js.map +1 -0
- package/dist/extension-sync.d.ts +111 -0
- package/dist/extension-sync.js +463 -0
- package/dist/extension-sync.js.map +1 -0
- package/dist/import.d.ts +39 -0
- package/dist/import.js +244 -0
- package/dist/import.js.map +1 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +18 -0
- package/dist/npm-extension-source.d.ts +13 -0
- package/dist/npm-extension-source.js +63 -0
- package/dist/npm-extension-source.js.map +1 -0
- package/dist/output-safety.d.ts +29 -0
- package/dist/output-safety.js +213 -0
- package/dist/output-safety.js.map +1 -0
- package/dist/project-asset-additions.d.ts +29 -0
- package/dist/project-asset-additions.js +412 -0
- package/dist/project-asset-additions.js.map +1 -0
- package/dist/release-snapshot.d.ts +75 -0
- package/dist/release-snapshot.js +177 -0
- package/dist/release-snapshot.js.map +1 -0
- package/dist/source.d.ts +41 -0
- package/dist/source.js +282 -0
- package/dist/source.js.map +1 -0
- package/dist/turbowarp-clean-up.d.ts +18 -0
- package/dist/turbowarp-clean-up.js +266 -0
- package/dist/turbowarp-clean-up.js.map +1 -0
- package/dist/types.d.ts +80 -0
- package/package.json +29 -21
- package/bin/sb3-toolchain.mjs +0 -9
- package/src/archive.js +0 -35
- package/src/build.js +0 -188
- package/src/cli.js +0 -748
- package/src/constants.js +0 -4
- package/src/extension-api-manifest.js +0 -336
- package/src/extension-bundle-archive.js +0 -422
- package/src/extension-bundle-configuration.js +0 -265
- package/src/extension-bundle.js +0 -695
- package/src/extension-dependencies.js +0 -114
- package/src/extension-id-migration.js +0 -496
- package/src/extension-sync.js +0 -754
- package/src/import.js +0 -397
- package/src/index.js +0 -75
- package/src/npm-extension-source.js +0 -111
- package/src/output-safety.js +0 -322
- package/src/project-asset-additions.js +0 -560
- package/src/release-snapshot.js +0 -247
- package/src/source.js +0 -468
- package/src/turbowarp-clean-up.js +0 -295
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { assert } from "./assert.js";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
6
|
+
//#region src/release-snapshot.ts
|
|
7
|
+
var releaseSnapshotFormatVersion = 1;
|
|
8
|
+
var releaseSnapshotStates = /* @__PURE__ */ new Set([
|
|
9
|
+
"candidate",
|
|
10
|
+
"frozen",
|
|
11
|
+
"published"
|
|
12
|
+
]);
|
|
13
|
+
function sha256(contents) {
|
|
14
|
+
return createHash("sha256").update(contents).digest("hex");
|
|
15
|
+
}
|
|
16
|
+
function asBuffer(contents, description) {
|
|
17
|
+
if (Buffer.isBuffer(contents)) return contents;
|
|
18
|
+
if (contents instanceof Uint8Array) return Buffer.from(contents);
|
|
19
|
+
if (typeof contents === "string") return Buffer.from(contents);
|
|
20
|
+
throw new TypeError(`${description} must be a string, Buffer, or Uint8Array.`);
|
|
21
|
+
}
|
|
22
|
+
function normalizedSourceEntries(sourceFiles) {
|
|
23
|
+
assert(sourceFiles instanceof Map, "Release source files must be provided as a Map.");
|
|
24
|
+
const entries = [...sourceFiles.entries()].map(([relativePath, contents]) => {
|
|
25
|
+
assert(typeof relativePath === "string" && relativePath.length > 0 && !path.isAbsolute(relativePath) && !relativePath.split(/[\\/]+/u).includes(".."), `Release source path must be a safe relative path: ${relativePath}`);
|
|
26
|
+
return [relativePath.split(path.sep).join("/"), asBuffer(contents, relativePath)];
|
|
27
|
+
});
|
|
28
|
+
entries.sort(([left], [right]) => left.localeCompare(right, "en"));
|
|
29
|
+
return entries;
|
|
30
|
+
}
|
|
31
|
+
function computeReleaseSourceIdentity(sourceFiles) {
|
|
32
|
+
const hash = createHash("sha256");
|
|
33
|
+
for (const [relativePath, contents] of normalizedSourceEntries(sourceFiles)) {
|
|
34
|
+
const pathBytes = Buffer.from(relativePath);
|
|
35
|
+
hash.update(Buffer.from(`${pathBytes.byteLength}:`));
|
|
36
|
+
hash.update(pathBytes);
|
|
37
|
+
hash.update(Buffer.from(`:${contents.byteLength}:`));
|
|
38
|
+
hash.update(contents);
|
|
39
|
+
}
|
|
40
|
+
return `sha256:${hash.digest("hex")}`;
|
|
41
|
+
}
|
|
42
|
+
function createSb3ReleaseSnapshotMetadata({ artifact, metadata = {}, publication = {}, sourceFiles, state = "candidate" }) {
|
|
43
|
+
assert(releaseSnapshotStates.has(state), `Unsupported SB3 release snapshot state: ${state}`);
|
|
44
|
+
const archive = asBuffer(artifact.archive, "SB3 release artifact archive");
|
|
45
|
+
const filename = artifact.filename;
|
|
46
|
+
assert(typeof filename === "string" && filename.endsWith(".sb3"), "Artifact filename is required.");
|
|
47
|
+
const normalizedArtifact = {
|
|
48
|
+
filename,
|
|
49
|
+
sha256: sha256(archive),
|
|
50
|
+
size: archive.byteLength
|
|
51
|
+
};
|
|
52
|
+
if (artifact.url !== void 0) {
|
|
53
|
+
const url = new URL(artifact.url);
|
|
54
|
+
assert(url.protocol === "https:", "Artifact URL must use HTTPS.");
|
|
55
|
+
normalizedArtifact.url = url.href;
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
formatVersion: releaseSnapshotFormatVersion,
|
|
59
|
+
...metadata,
|
|
60
|
+
state,
|
|
61
|
+
sourceIdentity: computeReleaseSourceIdentity(sourceFiles),
|
|
62
|
+
artifact: normalizedArtifact,
|
|
63
|
+
publication: { ...publication }
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function assertSb3ReleaseSnapshotMetadata(value) {
|
|
67
|
+
const metadata = value;
|
|
68
|
+
assert(metadata?.formatVersion === releaseSnapshotFormatVersion, "SB3 release snapshot metadata format is invalid.");
|
|
69
|
+
assert(releaseSnapshotStates.has(metadata.state), "SB3 release snapshot state is invalid.");
|
|
70
|
+
assert(typeof metadata.sourceIdentity === "string" && /^sha256:[0-9a-f]{64}$/u.test(metadata.sourceIdentity), "SB3 release snapshot source identity is invalid.");
|
|
71
|
+
assert(typeof metadata.artifact?.filename === "string" && metadata.artifact.filename.endsWith(".sb3"), "SB3 release snapshot artifact filename is invalid.");
|
|
72
|
+
assert(typeof metadata.artifact?.sha256 === "string" && /^[0-9a-f]{64}$/u.test(metadata.artifact.sha256), "SB3 release snapshot artifact SHA-256 is invalid.");
|
|
73
|
+
assert(Number.isSafeInteger(metadata.artifact?.size) && metadata.artifact.size > 0, "SB3 release snapshot artifact size is invalid.");
|
|
74
|
+
if (metadata.artifact.url !== void 0) {
|
|
75
|
+
const url = new URL(metadata.artifact.url);
|
|
76
|
+
assert(url.protocol === "https:", "SB3 release snapshot artifact URL must use HTTPS.");
|
|
77
|
+
}
|
|
78
|
+
if (metadata.publication?.urls !== void 0) for (const [name, value] of Object.entries(metadata.publication.urls)) {
|
|
79
|
+
const url = new URL(value);
|
|
80
|
+
assert(url.protocol === "https:", `SB3 release snapshot publication URL must use HTTPS: ${name}`);
|
|
81
|
+
}
|
|
82
|
+
return metadata;
|
|
83
|
+
}
|
|
84
|
+
async function createSb3ReleaseSnapshot({ artifact, createSb3, metadata, publication, sourceFiles, state }) {
|
|
85
|
+
assert(typeof createSb3 === "function", "A createSb3 function is required.");
|
|
86
|
+
const archive = asBuffer((await createSb3()).archive, "SB3 release artifact archive");
|
|
87
|
+
return {
|
|
88
|
+
archive,
|
|
89
|
+
metadata: assertSb3ReleaseSnapshotMetadata(createSb3ReleaseSnapshotMetadata({
|
|
90
|
+
artifact: {
|
|
91
|
+
...artifact,
|
|
92
|
+
archive
|
|
93
|
+
},
|
|
94
|
+
metadata,
|
|
95
|
+
publication,
|
|
96
|
+
sourceFiles,
|
|
97
|
+
state
|
|
98
|
+
})),
|
|
99
|
+
sourceFiles
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
async function verifySb3ReleaseSnapshot(options) {
|
|
103
|
+
const { createSb3, fetchPublishedArtifact, metadata, sourceFiles } = options;
|
|
104
|
+
const snapshot = assertSb3ReleaseSnapshotMetadata(metadata);
|
|
105
|
+
if (snapshot.state === "published") {
|
|
106
|
+
assert(typeof fetchPublishedArtifact === "function", "A published artifact fetcher is required.");
|
|
107
|
+
const archive = asBuffer(await fetchPublishedArtifact(snapshot), "Published SB3 release artifact");
|
|
108
|
+
assert(archive.byteLength === snapshot.artifact.size, "Published SB3 release artifact size is invalid.");
|
|
109
|
+
assert(sha256(archive) === snapshot.artifact.sha256, "Published SB3 release artifact SHA-256 is invalid.");
|
|
110
|
+
return snapshot;
|
|
111
|
+
}
|
|
112
|
+
assert(sourceFiles !== void 0 && computeReleaseSourceIdentity(sourceFiles) === snapshot.sourceIdentity, "SB3 release source changed. Update the release snapshot.");
|
|
113
|
+
assert(typeof createSb3 === "function", "A createSb3 function is required.");
|
|
114
|
+
const [first, second] = await Promise.all([createSb3(), createSb3()]);
|
|
115
|
+
const firstArchive = asBuffer(first.archive, "First SB3 release artifact archive");
|
|
116
|
+
const secondArchive = asBuffer(second.archive, "Second SB3 release artifact archive");
|
|
117
|
+
assert(firstArchive.equals(secondArchive), "SB3 release artifact generation is not deterministic.");
|
|
118
|
+
assert(sha256(firstArchive) === snapshot.artifact.sha256, "SB3 release artifact SHA-256 is stale.");
|
|
119
|
+
assert(firstArchive.byteLength === snapshot.artifact.size, "SB3 release artifact size is stale.");
|
|
120
|
+
return snapshot;
|
|
121
|
+
}
|
|
122
|
+
async function writeAtomically(filename, contents) {
|
|
123
|
+
await mkdir(path.dirname(filename), { recursive: true });
|
|
124
|
+
const temporaryPath = `${filename}.tmp-${process.pid}`;
|
|
125
|
+
try {
|
|
126
|
+
await writeFile(temporaryPath, contents);
|
|
127
|
+
await rename(temporaryPath, filename);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
await rm(temporaryPath, { force: true });
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async function writeSb3ReleaseCandidate({ artifactPath, archive, metadata, metadataPath }) {
|
|
134
|
+
assertSb3ReleaseSnapshotMetadata(metadata);
|
|
135
|
+
const artifactArchive = asBuffer(archive, "SB3 release candidate archive");
|
|
136
|
+
assert(sha256(artifactArchive) === metadata.artifact.sha256 && artifactArchive.byteLength === metadata.artifact.size, "SB3 release candidate archive does not match metadata.");
|
|
137
|
+
await writeAtomically(artifactPath, artifactArchive);
|
|
138
|
+
await writeAtomically(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`);
|
|
139
|
+
return {
|
|
140
|
+
artifactPath,
|
|
141
|
+
metadataPath
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
function freezeSb3ReleaseSnapshot(metadata) {
|
|
145
|
+
const snapshot = assertSb3ReleaseSnapshotMetadata(metadata);
|
|
146
|
+
if (snapshot.state === "frozen") return snapshot;
|
|
147
|
+
assert(snapshot.state === "candidate", "Only candidate SB3 release snapshots can be frozen.");
|
|
148
|
+
return assertSb3ReleaseSnapshotMetadata({
|
|
149
|
+
...snapshot,
|
|
150
|
+
state: "frozen"
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
async function readSb3ReleaseSnapshotMetadata(metadataPath) {
|
|
154
|
+
return assertSb3ReleaseSnapshotMetadata(JSON.parse(await readFile(metadataPath, "utf8")));
|
|
155
|
+
}
|
|
156
|
+
async function recordPublishedSb3ReleaseSnapshot(metadata, urls, options = {}) {
|
|
157
|
+
const { fetchPublishedArtifact } = options;
|
|
158
|
+
const snapshot = assertSb3ReleaseSnapshotMetadata(metadata);
|
|
159
|
+
assert(snapshot.state === "frozen", "Only frozen SB3 release snapshots can be published.");
|
|
160
|
+
const published = assertSb3ReleaseSnapshotMetadata({
|
|
161
|
+
...snapshot,
|
|
162
|
+
state: "published",
|
|
163
|
+
publication: {
|
|
164
|
+
...snapshot.publication,
|
|
165
|
+
urls
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
await verifySb3ReleaseSnapshot({
|
|
169
|
+
fetchPublishedArtifact,
|
|
170
|
+
metadata: published
|
|
171
|
+
});
|
|
172
|
+
return published;
|
|
173
|
+
}
|
|
174
|
+
//#endregion
|
|
175
|
+
export { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
|
|
176
|
+
|
|
177
|
+
//# sourceMappingURL=release-snapshot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"release-snapshot.js","names":[],"sources":["../src/release-snapshot.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {mkdir, readFile, rename, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\n\nimport {assert} from './assert';\nimport type {UnknownRecord} from './types';\n\nconst releaseSnapshotFormatVersion = 1;\nconst releaseSnapshotStates = new Set(['candidate', 'frozen', 'published']);\n\nexport type ReleaseSnapshotState = 'candidate' | 'frozen' | 'published';\n\nexport type ReleaseSourceFiles = Map<string, Buffer | Uint8Array | string>;\n\nexport interface ReleaseSnapshotArtifact {\n filename: string;\n sha256: string;\n size: number;\n url?: string;\n}\n\nexport interface ReleaseSnapshotPublication {\n urls?: Record<string, string>;\n [key: string]: unknown;\n}\n\nexport interface Sb3ReleaseSnapshotMetadata {\n artifact: ReleaseSnapshotArtifact;\n formatVersion: number;\n publication: ReleaseSnapshotPublication;\n sourceIdentity: string;\n state: ReleaseSnapshotState;\n [key: string]: unknown;\n}\n\nexport interface CreateReleaseSnapshotMetadataInput {\n artifact: {archive: Buffer | Uint8Array | string; filename: string; url?: string};\n metadata?: UnknownRecord;\n publication?: ReleaseSnapshotPublication;\n sourceFiles: ReleaseSourceFiles;\n state?: ReleaseSnapshotState;\n}\n\nexport interface BuiltReleaseArtifact {\n archive: Buffer | Uint8Array | string;\n}\n\nexport interface CreateReleaseSnapshotInput {\n artifact: {filename: string; url?: string};\n createSb3: () => BuiltReleaseArtifact | Promise<BuiltReleaseArtifact>;\n metadata?: UnknownRecord;\n publication?: ReleaseSnapshotPublication;\n sourceFiles: ReleaseSourceFiles;\n state?: ReleaseSnapshotState;\n}\n\nexport interface VerifyReleaseSnapshotOptions {\n createSb3?: () => BuiltReleaseArtifact | Promise<BuiltReleaseArtifact>;\n fetchPublishedArtifact?: (\n snapshot: Sb3ReleaseSnapshotMetadata,\n ) => Buffer | Uint8Array | string | Promise<Buffer | Uint8Array | string>;\n metadata: unknown;\n sourceFiles?: ReleaseSourceFiles;\n}\n\nfunction sha256(contents: Buffer | Uint8Array | string): string {\n return createHash('sha256').update(contents).digest('hex');\n}\n\nfunction asBuffer(contents: unknown, description: string): Buffer {\n if (Buffer.isBuffer(contents)) return contents;\n if (contents instanceof Uint8Array) return Buffer.from(contents);\n if (typeof contents === 'string') return Buffer.from(contents);\n throw new TypeError(`${description} must be a string, Buffer, or Uint8Array.`);\n}\n\nfunction normalizedSourceEntries(sourceFiles: unknown): [string, Buffer][] {\n assert(sourceFiles instanceof Map, 'Release source files must be provided as a Map.');\n const entries: [string, Buffer][] = [...sourceFiles.entries()].map(([relativePath, contents]) => {\n assert(\n typeof relativePath === 'string' &&\n relativePath.length > 0 &&\n !path.isAbsolute(relativePath) &&\n !relativePath.split(/[\\\\/]+/u).includes('..'),\n `Release source path must be a safe relative path: ${relativePath}`,\n );\n return [relativePath.split(path.sep).join('/'), asBuffer(contents, relativePath)];\n });\n entries.sort(([left], [right]) => left.localeCompare(right, 'en'));\n return entries;\n}\n\nexport function computeReleaseSourceIdentity(sourceFiles: ReleaseSourceFiles): string {\n const hash = createHash('sha256');\n for (const [relativePath, contents] of normalizedSourceEntries(sourceFiles)) {\n const pathBytes = Buffer.from(relativePath);\n hash.update(Buffer.from(`${pathBytes.byteLength}:`));\n hash.update(pathBytes);\n hash.update(Buffer.from(`:${contents.byteLength}:`));\n hash.update(contents);\n }\n return `sha256:${hash.digest('hex')}`;\n}\n\nexport function createSb3ReleaseSnapshotMetadata({\n artifact,\n metadata = {},\n publication = {},\n sourceFiles,\n state = 'candidate',\n}: CreateReleaseSnapshotMetadataInput): Sb3ReleaseSnapshotMetadata {\n assert(releaseSnapshotStates.has(state), `Unsupported SB3 release snapshot state: ${state}`);\n const archive = asBuffer(artifact.archive, 'SB3 release artifact archive');\n const filename = artifact.filename;\n assert(\n typeof filename === 'string' && filename.endsWith('.sb3'),\n 'Artifact filename is required.',\n );\n const normalizedArtifact: ReleaseSnapshotArtifact = {\n filename,\n sha256: sha256(archive),\n size: archive.byteLength,\n };\n if (artifact.url !== undefined) {\n const url = new URL(artifact.url);\n assert(url.protocol === 'https:', 'Artifact URL must use HTTPS.');\n normalizedArtifact.url = url.href;\n }\n return {\n formatVersion: releaseSnapshotFormatVersion,\n ...metadata,\n state,\n sourceIdentity: computeReleaseSourceIdentity(sourceFiles),\n artifact: normalizedArtifact,\n publication: {...publication},\n };\n}\n\nexport function assertSb3ReleaseSnapshotMetadata(value: unknown): Sb3ReleaseSnapshotMetadata {\n const metadata = value as Sb3ReleaseSnapshotMetadata | null | undefined;\n assert(\n metadata?.formatVersion === releaseSnapshotFormatVersion,\n 'SB3 release snapshot metadata format is invalid.',\n );\n assert(releaseSnapshotStates.has(metadata.state), 'SB3 release snapshot state is invalid.');\n assert(\n typeof metadata.sourceIdentity === 'string' &&\n /^sha256:[0-9a-f]{64}$/u.test(metadata.sourceIdentity),\n 'SB3 release snapshot source identity is invalid.',\n );\n assert(\n typeof metadata.artifact?.filename === 'string' && metadata.artifact.filename.endsWith('.sb3'),\n 'SB3 release snapshot artifact filename is invalid.',\n );\n assert(\n typeof metadata.artifact?.sha256 === 'string' &&\n /^[0-9a-f]{64}$/u.test(metadata.artifact.sha256),\n 'SB3 release snapshot artifact SHA-256 is invalid.',\n );\n assert(\n Number.isSafeInteger(metadata.artifact?.size) && metadata.artifact.size > 0,\n 'SB3 release snapshot artifact size is invalid.',\n );\n if (metadata.artifact.url !== undefined) {\n const url = new URL(metadata.artifact.url);\n assert(url.protocol === 'https:', 'SB3 release snapshot artifact URL must use HTTPS.');\n }\n if (metadata.publication?.urls !== undefined) {\n for (const [name, value] of Object.entries(metadata.publication.urls)) {\n const url = new URL(value);\n assert(\n url.protocol === 'https:',\n `SB3 release snapshot publication URL must use HTTPS: ${name}`,\n );\n }\n }\n return metadata;\n}\n\nexport async function createSb3ReleaseSnapshot({\n artifact,\n createSb3,\n metadata,\n publication,\n sourceFiles,\n state,\n}: CreateReleaseSnapshotInput): Promise<{\n archive: Buffer;\n metadata: Sb3ReleaseSnapshotMetadata;\n sourceFiles: ReleaseSourceFiles;\n}> {\n assert(typeof createSb3 === 'function', 'A createSb3 function is required.');\n const built = await createSb3();\n const archive = asBuffer(built.archive, 'SB3 release artifact archive');\n const snapshot = createSb3ReleaseSnapshotMetadata({\n artifact: {...artifact, archive},\n metadata,\n publication,\n sourceFiles,\n state,\n });\n return {archive, metadata: assertSb3ReleaseSnapshotMetadata(snapshot), sourceFiles};\n}\n\nexport async function verifySb3ReleaseSnapshot(\n options: VerifyReleaseSnapshotOptions,\n): Promise<Sb3ReleaseSnapshotMetadata> {\n const {createSb3, fetchPublishedArtifact, metadata, sourceFiles} = options;\n const snapshot = assertSb3ReleaseSnapshotMetadata(metadata);\n if (snapshot.state === 'published') {\n assert(\n typeof fetchPublishedArtifact === 'function',\n 'A published artifact fetcher is required.',\n );\n const archive = asBuffer(\n await fetchPublishedArtifact(snapshot),\n 'Published SB3 release artifact',\n );\n assert(\n archive.byteLength === snapshot.artifact.size,\n 'Published SB3 release artifact size is invalid.',\n );\n assert(\n sha256(archive) === snapshot.artifact.sha256,\n 'Published SB3 release artifact SHA-256 is invalid.',\n );\n return snapshot;\n }\n\n assert(\n sourceFiles !== undefined &&\n computeReleaseSourceIdentity(sourceFiles) === snapshot.sourceIdentity,\n 'SB3 release source changed. Update the release snapshot.',\n );\n assert(typeof createSb3 === 'function', 'A createSb3 function is required.');\n const [first, second] = await Promise.all([createSb3(), createSb3()]);\n const firstArchive = asBuffer(first.archive, 'First SB3 release artifact archive');\n const secondArchive = asBuffer(second.archive, 'Second SB3 release artifact archive');\n assert(\n firstArchive.equals(secondArchive),\n 'SB3 release artifact generation is not deterministic.',\n );\n assert(\n sha256(firstArchive) === snapshot.artifact.sha256,\n 'SB3 release artifact SHA-256 is stale.',\n );\n assert(firstArchive.byteLength === snapshot.artifact.size, 'SB3 release artifact size is stale.');\n return snapshot;\n}\n\nasync function writeAtomically(filename: string, contents: Buffer | string): Promise<void> {\n await mkdir(path.dirname(filename), {recursive: true});\n const temporaryPath = `${filename}.tmp-${process.pid}`;\n try {\n await writeFile(temporaryPath, contents);\n await rename(temporaryPath, filename);\n } catch (error) {\n await rm(temporaryPath, {force: true});\n throw error;\n }\n}\n\nexport async function writeSb3ReleaseCandidate({\n artifactPath,\n archive,\n metadata,\n metadataPath,\n}: {\n artifactPath: string;\n archive: Buffer | Uint8Array | string;\n metadata: Sb3ReleaseSnapshotMetadata;\n metadataPath: string;\n}): Promise<{artifactPath: string; metadataPath: string}> {\n assertSb3ReleaseSnapshotMetadata(metadata);\n const artifactArchive = asBuffer(archive, 'SB3 release candidate archive');\n assert(\n sha256(artifactArchive) === metadata.artifact.sha256 &&\n artifactArchive.byteLength === metadata.artifact.size,\n 'SB3 release candidate archive does not match metadata.',\n );\n await writeAtomically(artifactPath, artifactArchive);\n await writeAtomically(metadataPath, `${JSON.stringify(metadata, null, 2)}\\n`);\n return {artifactPath, metadataPath};\n}\n\nexport function freezeSb3ReleaseSnapshot(metadata: unknown): Sb3ReleaseSnapshotMetadata {\n const snapshot = assertSb3ReleaseSnapshotMetadata(metadata);\n if (snapshot.state === 'frozen') return snapshot;\n assert(snapshot.state === 'candidate', 'Only candidate SB3 release snapshots can be frozen.');\n return assertSb3ReleaseSnapshotMetadata({...snapshot, state: 'frozen'});\n}\n\nexport async function readSb3ReleaseSnapshotMetadata(\n metadataPath: string,\n): Promise<Sb3ReleaseSnapshotMetadata> {\n return assertSb3ReleaseSnapshotMetadata(JSON.parse(await readFile(metadataPath, 'utf8')));\n}\n\nexport async function recordPublishedSb3ReleaseSnapshot(\n metadata: unknown,\n urls: Record<string, string>,\n options: {fetchPublishedArtifact?: VerifyReleaseSnapshotOptions['fetchPublishedArtifact']} = {},\n): Promise<Sb3ReleaseSnapshotMetadata> {\n const {fetchPublishedArtifact} = options;\n const snapshot = assertSb3ReleaseSnapshotMetadata(metadata);\n assert(snapshot.state === 'frozen', 'Only frozen SB3 release snapshots can be published.');\n const published = assertSb3ReleaseSnapshotMetadata({\n ...snapshot,\n state: 'published',\n publication: {\n ...snapshot.publication,\n urls,\n },\n });\n await verifySb3ReleaseSnapshot({\n fetchPublishedArtifact,\n metadata: published,\n });\n return published;\n}\n"],"mappings":";;;;;;AAUA,IAAM,+BAA+B;AACrC,IAAM,wCAAwB,IAAI,IAAI;CAAC;CAAa;CAAU;AAAW,CAAC;AAyD1E,SAAS,OAAO,UAAgD;CAC9D,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,OAAO,KAAK;AAC3D;AAEA,SAAS,SAAS,UAAmB,aAA6B;CAChE,IAAI,OAAO,SAAS,QAAQ,GAAG,OAAO;CACtC,IAAI,oBAAoB,YAAY,OAAO,OAAO,KAAK,QAAQ;CAC/D,IAAI,OAAO,aAAa,UAAU,OAAO,OAAO,KAAK,QAAQ;CAC7D,MAAM,IAAI,UAAU,GAAG,YAAY,0CAA0C;AAC/E;AAEA,SAAS,wBAAwB,aAA0C;CACzE,OAAO,uBAAuB,KAAK,iDAAiD;CACpF,MAAM,UAA8B,CAAC,GAAG,YAAY,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,cAAc,cAAc;EAC/F,OACE,OAAO,iBAAiB,YACtB,aAAa,SAAS,KACtB,CAAC,KAAK,WAAW,YAAY,KAC7B,CAAC,aAAa,MAAM,SAAS,CAAC,CAAC,SAAS,IAAI,GAC9C,qDAAqD,cACvD;EACA,OAAO,CAAC,aAAa,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG,GAAG,SAAS,UAAU,YAAY,CAAC;CAClF,CAAC;CACD,QAAQ,MAAM,CAAC,OAAO,CAAC,WAAW,KAAK,cAAc,OAAO,IAAI,CAAC;CACjE,OAAO;AACT;AAEA,SAAgB,6BAA6B,aAAyC;CACpF,MAAM,OAAO,WAAW,QAAQ;CAChC,KAAK,MAAM,CA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CAAiC,KAAK,MAAM,MAAM,SAAS,cAAc,MAAM,CAAC,CAAC;AAC1F;AAEA,eAAsB,kCACpB,UACA,MACA,UAA6F,CAAC,GACzD;CACrC,MAAM,EAAC,2BAA0B;CACjC,MAAM,WAAW,iCAAiC,QAAQ;CAC1D,OAAO,SAAS,UAAU,UAAU,qDAAqD;CACzF,MAAM,YAAY,iCAAiC;EACjD,GAAG;EACH,OAAO;EACP,aAAa;GACX,GAAG,SAAS;GACZ;EACF;CACF,CAAC;CACD,MAAM,yBAAyB;EAC7B;EACA,UAAU;CACZ,CAAC;CACD,OAAO;AACT"}
|
package/dist/source.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { ExtensionBundlePlan } from './extension-bundle';
|
|
2
|
+
import { ProjectAssetAdditionsSummary } from './project-asset-additions';
|
|
3
|
+
import { EmbeddedExtension, ExtensionBundleConfiguration, ProjectJson, Sb3SourceManifest } from './types';
|
|
4
|
+
export declare const sourceFormatVersion = 1;
|
|
5
|
+
export declare const fixedZipTimestamp: Date;
|
|
6
|
+
export interface InspectedSb3Source {
|
|
7
|
+
assetContents: Map<string, Uint8Array>;
|
|
8
|
+
assetReferenceCount: number;
|
|
9
|
+
extensions: EmbeddedExtension[];
|
|
10
|
+
extensionApiManifestContents: Map<string, Uint8Array>;
|
|
11
|
+
extensionBundles: ExtensionBundleConfiguration[];
|
|
12
|
+
extensionContents: Map<string, Uint8Array>;
|
|
13
|
+
project: ProjectJson;
|
|
14
|
+
resolvedSourceDirectory: string;
|
|
15
|
+
sourceManifest: Sb3SourceManifest;
|
|
16
|
+
}
|
|
17
|
+
export interface BlockCleanUpSummary {
|
|
18
|
+
movedCommentCount: number;
|
|
19
|
+
movedScriptCount: number;
|
|
20
|
+
scriptCount: number;
|
|
21
|
+
targetCount: number;
|
|
22
|
+
}
|
|
23
|
+
export interface DeterministicSb3Options {
|
|
24
|
+
allowedAssetRoots?: string[];
|
|
25
|
+
cleanUpBlocks?: boolean;
|
|
26
|
+
projectAssetsPath?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface DeterministicSb3 {
|
|
29
|
+
archive: Uint8Array;
|
|
30
|
+
assetCount: number;
|
|
31
|
+
assetReferenceCount: number;
|
|
32
|
+
blockCleanUp: BlockCleanUpSummary | null;
|
|
33
|
+
bundlePlans: ExtensionBundlePlan[];
|
|
34
|
+
embeddedExtensionCount: number;
|
|
35
|
+
entryCount: number;
|
|
36
|
+
projectAssetAdditions: Readonly<ProjectAssetAdditionsSummary> | null;
|
|
37
|
+
source: InspectedSb3Source;
|
|
38
|
+
}
|
|
39
|
+
export declare function inspectSb3SourceForExtensionSync(sourceDirectory: string): Promise<InspectedSb3Source>;
|
|
40
|
+
export declare function validateSb3Source(sourceDirectory: string): Promise<InspectedSb3Source>;
|
|
41
|
+
export declare function createDeterministicSb3(sourceDirectory: string, options?: DeterministicSb3Options): Promise<DeterministicSb3>;
|
package/dist/source.js
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { assert, errorMessage } from "./assert.js";
|
|
2
|
+
import { validateArchiveEntryName } from "./archive.js";
|
|
3
|
+
import { validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
|
|
4
|
+
import { validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
|
|
5
|
+
import { buildExtensionBundles, validateExtensionBundleConfigurations } from "./extension-bundle.js";
|
|
6
|
+
import { applyProjectAssetAdditions } from "./project-asset-additions.js";
|
|
7
|
+
import { cleanUpTurboWarpBlocks } from "./turbowarp-clean-up.js";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { lstat, readFile, readdir } from "node:fs/promises";
|
|
11
|
+
import { strToU8, zipSync } from "fflate";
|
|
12
|
+
//#region src/source.ts
|
|
13
|
+
var sourceFormatVersion = 1;
|
|
14
|
+
var fixedZipTimestamp = new Date(1980, 0, 1, 0, 0, 0, 0);
|
|
15
|
+
function isObject(value) {
|
|
16
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
17
|
+
}
|
|
18
|
+
async function readJson(filePath, description) {
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(await readFile(filePath, "utf8"));
|
|
21
|
+
} catch (error) {
|
|
22
|
+
throw new Error(`${description} is not valid JSON: ${filePath} (${errorMessage(error)})`, { cause: error });
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
async function assertDirectory(directoryPath, description) {
|
|
26
|
+
const stats = await lstat(directoryPath);
|
|
27
|
+
assert(stats.isDirectory() && !stats.isSymbolicLink(), `${description} must be a directory, not a file or symbolic link: ${directoryPath}`);
|
|
28
|
+
}
|
|
29
|
+
async function listRegularFiles(rootDirectory, description) {
|
|
30
|
+
await assertDirectory(rootDirectory, description);
|
|
31
|
+
const files = [];
|
|
32
|
+
async function visit(directory, relativeDirectory) {
|
|
33
|
+
const entries = await readdir(directory, { withFileTypes: true });
|
|
34
|
+
entries.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
|
|
35
|
+
for (const entry of entries) {
|
|
36
|
+
const relativePath = relativeDirectory ? path.posix.join(relativeDirectory, entry.name) : entry.name;
|
|
37
|
+
const absolutePath = path.join(directory, entry.name);
|
|
38
|
+
if (entry.isDirectory()) await visit(absolutePath, relativePath);
|
|
39
|
+
else {
|
|
40
|
+
assert(entry.isFile(), `${description} contains a symbolic link or unsupported entry: ${relativePath}`);
|
|
41
|
+
files.push(relativePath);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
await visit(rootDirectory, "");
|
|
46
|
+
return files;
|
|
47
|
+
}
|
|
48
|
+
function assertSameFileSet(actualFiles, expectedFiles, description) {
|
|
49
|
+
const actual = new Set(actualFiles);
|
|
50
|
+
const expected = new Set(expectedFiles);
|
|
51
|
+
const missing = [...expected].filter((filePath) => !actual.has(filePath)).sort();
|
|
52
|
+
const extra = [...actual].filter((filePath) => !expected.has(filePath)).sort();
|
|
53
|
+
assert(missing.length === 0 && extra.length === 0, `${description} does not match its manifest. Missing: ${missing.join(", ") || "(none)"}. Extra: ${extra.join(", ") || "(none)"}.`);
|
|
54
|
+
}
|
|
55
|
+
function md5(contents) {
|
|
56
|
+
return createHash("md5").update(contents).digest("hex");
|
|
57
|
+
}
|
|
58
|
+
function validateSourceManifest(manifest) {
|
|
59
|
+
assert(isObject(manifest), "sb3-source.json must contain an object.");
|
|
60
|
+
assert(manifest.formatVersion === 1, `Unsupported SB3 source format version: ${manifest.formatVersion}`);
|
|
61
|
+
assert(manifest.project === "project.source.json", "SB3 source format 1 requires project.source.json.");
|
|
62
|
+
assert(manifest.embeddedExtensions === "embedded-extensions.json", "SB3 source format 1 requires embedded-extensions.json.");
|
|
63
|
+
assert(manifest.assetsDirectory === "assets", "SB3 source format 1 requires the assets directory.");
|
|
64
|
+
assert(Array.isArray(manifest.archiveEntries) && manifest.archiveEntries.length > 0, "sb3-source.json archiveEntries must be a non-empty array.");
|
|
65
|
+
const seenEntries = /* @__PURE__ */ new Set();
|
|
66
|
+
let projectEntryCount = 0;
|
|
67
|
+
for (const rawEntryName of manifest.archiveEntries) {
|
|
68
|
+
const entryName = validateArchiveEntryName(rawEntryName);
|
|
69
|
+
assert(!seenEntries.has(entryName), `Duplicate archive entry in manifest: ${entryName}`);
|
|
70
|
+
assert(!entryName.endsWith("/"), `Directory ZIP entries are not supported in SB3 source format 1: ${entryName}`);
|
|
71
|
+
assert(!/^(?:0|[1-9][0-9]*)$/u.test(entryName), `Integer-like ZIP entry names cannot preserve JavaScript object order: ${entryName}`);
|
|
72
|
+
seenEntries.add(entryName);
|
|
73
|
+
if (entryName === "project.json") projectEntryCount += 1;
|
|
74
|
+
}
|
|
75
|
+
assert(projectEntryCount === 1, "archiveEntries must contain project.json exactly once.");
|
|
76
|
+
}
|
|
77
|
+
function validateExtensionManifest(extensionManifest, project, extensionFiles) {
|
|
78
|
+
assert(isObject(extensionManifest), "embedded-extensions.json must contain an object.");
|
|
79
|
+
assert(extensionManifest.formatVersion === 1, `Unsupported embedded extension manifest version: ${extensionManifest.formatVersion}`);
|
|
80
|
+
assert(Array.isArray(extensionManifest.extensions), "embedded-extensions.json extensions must be an array.");
|
|
81
|
+
const extensionUrls = project.extensionURLs ?? {};
|
|
82
|
+
assert(isObject(extensionUrls), "project.source.json extensionURLs must be an object when present.");
|
|
83
|
+
const extensionsById = /* @__PURE__ */ new Map();
|
|
84
|
+
const expectedFiles = [];
|
|
85
|
+
const extensions = [];
|
|
86
|
+
for (const entry of extensionManifest.extensions) {
|
|
87
|
+
assert(isObject(entry), "Each embedded extension manifest entry must be an object.");
|
|
88
|
+
const extension = entry;
|
|
89
|
+
assert(typeof extension.id === "string" && /^[A-Za-z0-9._-]+$/u.test(extension.id), `Invalid embedded extension ID: ${JSON.stringify(extension.id)}`);
|
|
90
|
+
assert(!extensionsById.has(extension.id), `Duplicate embedded extension ID: ${extension.id}`);
|
|
91
|
+
const expectedPath = `extensions/${extension.id}.js`;
|
|
92
|
+
assert(extension.path === expectedPath, `Embedded extension path must match its ID: expected ${expectedPath}, got ${extension.path}`);
|
|
93
|
+
assert(typeof extension.mediaType === "string" && extension.mediaType.length > 0 && !/[;,\r\n]/u.test(extension.mediaType), `Invalid media type for embedded extension ${extension.id}: ${extension.mediaType}`);
|
|
94
|
+
assert(Array.isArray(extension.parameters) && extension.parameters.every((parameter) => typeof parameter === "string" && parameter.length > 0 && !/[;,\r\n]/u.test(parameter)), `Invalid data URL parameters for embedded extension ${extension.id}.`);
|
|
95
|
+
assert(extension.encoding === "base64" || extension.encoding === "percent", `Unsupported encoding for embedded extension ${extension.id}: ${extension.encoding}`);
|
|
96
|
+
assert(extensionUrls[extension.id] === `embedded-extension:${extension.path}`, `project.source.json mapping does not match embedded extension ${extension.id}.`);
|
|
97
|
+
validateExtensionSourceMetadata(extension);
|
|
98
|
+
extensionsById.set(extension.id, extension);
|
|
99
|
+
extensions.push(extension);
|
|
100
|
+
expectedFiles.push(`${extension.id}.js`);
|
|
101
|
+
if (extension.source?.apiManifest) expectedFiles.push(path.posix.relative("extensions", extension.source.apiManifest.path));
|
|
102
|
+
}
|
|
103
|
+
for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {
|
|
104
|
+
assert(typeof extensionUrl !== "string" || !extensionUrl.startsWith("data:"), `project.source.json still contains an embedded data URL: ${extensionId}`);
|
|
105
|
+
if (typeof extensionUrl === "string" && extensionUrl.startsWith("embedded-extension:")) assert(extensionsById.has(extensionId), `project.source.json has no metadata for embedded extension ${extensionId}.`);
|
|
106
|
+
}
|
|
107
|
+
assertSameFileSet(extensionFiles, expectedFiles, "Embedded extension files");
|
|
108
|
+
return {
|
|
109
|
+
extensionBundles: validateExtensionBundleConfigurations(extensionManifest.extensionBundles, extensions),
|
|
110
|
+
extensions
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function collectAssetReferences(project) {
|
|
114
|
+
assert(Array.isArray(project.targets), "project.source.json targets must be an array.");
|
|
115
|
+
const references = [];
|
|
116
|
+
for (const [targetIndex, target] of project.targets.entries()) {
|
|
117
|
+
assert(isObject(target), `Project target ${targetIndex} must be an object.`);
|
|
118
|
+
for (const [collectionName, kind] of [["costumes", "costume"], ["sounds", "sound"]]) {
|
|
119
|
+
const assets = target[collectionName] ?? [];
|
|
120
|
+
assert(Array.isArray(assets), `Project target ${targetIndex} ${collectionName} must be an array.`);
|
|
121
|
+
for (const [assetIndex, asset] of assets.entries()) {
|
|
122
|
+
assert(isObject(asset), `Project ${kind} ${targetIndex}:${assetIndex} must be an object.`);
|
|
123
|
+
references.push({
|
|
124
|
+
asset,
|
|
125
|
+
description: `${kind} ${targetIndex}:${assetIndex}`
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return references;
|
|
131
|
+
}
|
|
132
|
+
function percentEncode(contents) {
|
|
133
|
+
return [...contents].map((byte) => `%${byte.toString(16).padStart(2, "0").toUpperCase()}`).join("");
|
|
134
|
+
}
|
|
135
|
+
function encodeExtensionDataUrl(extension, contents) {
|
|
136
|
+
const metadata = [extension.mediaType, ...extension.parameters].join(";");
|
|
137
|
+
if (extension.encoding === "base64") return `data:${metadata};base64,${Buffer.from(contents).toString("base64")}`;
|
|
138
|
+
return `data:${metadata},${percentEncode(contents)}`;
|
|
139
|
+
}
|
|
140
|
+
async function inspectSb3Source(sourceDirectory, validateManagedExtensions) {
|
|
141
|
+
const resolvedSourceDirectory = path.resolve(sourceDirectory);
|
|
142
|
+
await assertDirectory(resolvedSourceDirectory, "SB3 source");
|
|
143
|
+
const sourceManifest = await readJson(path.join(resolvedSourceDirectory, "sb3-source.json"), "SB3 source manifest");
|
|
144
|
+
validateSourceManifest(sourceManifest);
|
|
145
|
+
const assetEntries = sourceManifest.archiveEntries.filter((entryName) => entryName !== "project.json");
|
|
146
|
+
const project = await readJson(path.join(resolvedSourceDirectory, sourceManifest.project), "SB3 project source");
|
|
147
|
+
assert(isObject(project), "project.source.json must contain an object.");
|
|
148
|
+
const extensionManifest = await readJson(path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions), "Embedded extension manifest");
|
|
149
|
+
const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);
|
|
150
|
+
const extensionsDirectory = path.join(resolvedSourceDirectory, "extensions");
|
|
151
|
+
const [assetFiles, extensionFiles] = await Promise.all([listRegularFiles(assetsDirectory, "Assets directory"), listRegularFiles(extensionsDirectory, "Extensions directory")]);
|
|
152
|
+
assertSameFileSet(assetFiles, assetEntries, "Asset files");
|
|
153
|
+
const { extensionBundles, extensions } = validateExtensionManifest(extensionManifest, project, extensionFiles);
|
|
154
|
+
const assetContents = /* @__PURE__ */ new Map();
|
|
155
|
+
await Promise.all(assetFiles.map(async (assetPath) => {
|
|
156
|
+
assetContents.set(assetPath, await readFile(path.join(assetsDirectory, assetPath)));
|
|
157
|
+
}));
|
|
158
|
+
const referencedAssets = /* @__PURE__ */ new Set();
|
|
159
|
+
const references = collectAssetReferences(project);
|
|
160
|
+
for (const { asset, description } of references) {
|
|
161
|
+
assert(typeof asset.assetId === "string" && /^[a-f0-9]{32}$/u.test(asset.assetId), `Invalid assetId for ${description}: ${asset.assetId}`);
|
|
162
|
+
assert(typeof asset.dataFormat === "string" && /^[A-Za-z0-9]+$/u.test(asset.dataFormat), `Invalid dataFormat for ${description}: ${asset.dataFormat}`);
|
|
163
|
+
const expectedFilename = `${asset.assetId}.${asset.dataFormat}`;
|
|
164
|
+
assert(asset.md5ext === expectedFilename, `Asset filename mismatch for ${description}: expected ${expectedFilename}, got ${asset.md5ext}`);
|
|
165
|
+
const contents = assetContents.get(expectedFilename);
|
|
166
|
+
assert(contents, `Referenced asset is missing for ${description}: ${expectedFilename}`);
|
|
167
|
+
const actualAssetId = md5(contents);
|
|
168
|
+
assert(actualAssetId === asset.assetId, `Asset content hash mismatch for ${description}: expected ${asset.assetId}, got ${actualAssetId}`);
|
|
169
|
+
referencedAssets.add(expectedFilename);
|
|
170
|
+
}
|
|
171
|
+
const unreferencedAssets = assetFiles.filter((assetPath) => !referencedAssets.has(assetPath));
|
|
172
|
+
assert(unreferencedAssets.length === 0, `Asset manifest contains unreferenced files: ${unreferencedAssets.join(", ")}`);
|
|
173
|
+
const extensionContents = /* @__PURE__ */ new Map();
|
|
174
|
+
const extensionApiManifestContents = /* @__PURE__ */ new Map();
|
|
175
|
+
await Promise.all(extensions.map(async (extension) => {
|
|
176
|
+
const contents = await readFile(path.join(resolvedSourceDirectory, extension.path));
|
|
177
|
+
if (validateManagedExtensions) validateManagedExtensionContents(extension, contents);
|
|
178
|
+
extensionContents.set(extension.id, contents);
|
|
179
|
+
if (extension.source?.apiManifest) {
|
|
180
|
+
const apiManifestContents = await readFile(path.join(resolvedSourceDirectory, extension.source.apiManifest.path));
|
|
181
|
+
if (validateManagedExtensions) validateManagedExtensionApiManifest(extension, apiManifestContents);
|
|
182
|
+
extensionApiManifestContents.set(extension.id, apiManifestContents);
|
|
183
|
+
}
|
|
184
|
+
}));
|
|
185
|
+
return {
|
|
186
|
+
assetContents,
|
|
187
|
+
assetReferenceCount: references.length,
|
|
188
|
+
extensions,
|
|
189
|
+
extensionApiManifestContents,
|
|
190
|
+
extensionBundles,
|
|
191
|
+
extensionContents,
|
|
192
|
+
project,
|
|
193
|
+
resolvedSourceDirectory,
|
|
194
|
+
sourceManifest
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
async function inspectSb3SourceForExtensionSync(sourceDirectory) {
|
|
198
|
+
return inspectSb3Source(sourceDirectory, false);
|
|
199
|
+
}
|
|
200
|
+
async function validateSb3Source(sourceDirectory) {
|
|
201
|
+
const source = await inspectSb3Source(sourceDirectory, true);
|
|
202
|
+
buildExtensionBundles({
|
|
203
|
+
extensionBundles: source.extensionBundles,
|
|
204
|
+
extensionContents: source.extensionContents,
|
|
205
|
+
extensions: source.extensions,
|
|
206
|
+
project: source.project
|
|
207
|
+
});
|
|
208
|
+
return source;
|
|
209
|
+
}
|
|
210
|
+
async function createDeterministicSb3(sourceDirectory, options = {}) {
|
|
211
|
+
const { allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath } = options;
|
|
212
|
+
assert(typeof cleanUpBlocks === "boolean", "cleanUpBlocks must be a boolean.");
|
|
213
|
+
assert(Array.isArray(allowedAssetRoots), "allowedAssetRoots must be an array.");
|
|
214
|
+
assert(projectAssetsPath === void 0 || typeof projectAssetsPath === "string", "projectAssetsPath must be a string when provided.");
|
|
215
|
+
const source = await validateSb3Source(sourceDirectory);
|
|
216
|
+
const projectAssets = projectAssetsPath ? await applyProjectAssetAdditions({
|
|
217
|
+
allowedAssetRoots,
|
|
218
|
+
assetContents: source.assetContents,
|
|
219
|
+
archiveEntries: source.sourceManifest.archiveEntries,
|
|
220
|
+
manifestPath: projectAssetsPath,
|
|
221
|
+
project: source.project
|
|
222
|
+
}) : {
|
|
223
|
+
archiveEntries: source.sourceManifest.archiveEntries,
|
|
224
|
+
assetContents: source.assetContents,
|
|
225
|
+
assetReferenceCount: 0,
|
|
226
|
+
project: source.project,
|
|
227
|
+
summary: null
|
|
228
|
+
};
|
|
229
|
+
const bundled = buildExtensionBundles({
|
|
230
|
+
extensionBundles: source.extensionBundles,
|
|
231
|
+
extensionContents: source.extensionContents,
|
|
232
|
+
extensions: source.extensions,
|
|
233
|
+
project: projectAssets.project
|
|
234
|
+
});
|
|
235
|
+
let project = structuredClone(bundled.project);
|
|
236
|
+
let blockCleanUp = null;
|
|
237
|
+
if (cleanUpBlocks) {
|
|
238
|
+
const cleaned = cleanUpTurboWarpBlocks(project);
|
|
239
|
+
project = cleaned.project;
|
|
240
|
+
blockCleanUp = {
|
|
241
|
+
movedCommentCount: cleaned.movedCommentCount,
|
|
242
|
+
movedScriptCount: cleaned.movedScriptCount,
|
|
243
|
+
scriptCount: cleaned.scriptCount,
|
|
244
|
+
targetCount: cleaned.targetCount
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
const extensionUrls = project.extensionURLs ?? {};
|
|
248
|
+
for (const extension of bundled.extensions) {
|
|
249
|
+
const contents = bundled.extensionContents.get(extension.id);
|
|
250
|
+
assert(contents, `Embedded extension has no contents: ${extension.id}`);
|
|
251
|
+
extensionUrls[extension.id] = encodeExtensionDataUrl(extension, contents);
|
|
252
|
+
}
|
|
253
|
+
project.extensionURLs = extensionUrls;
|
|
254
|
+
const archiveEntries = {};
|
|
255
|
+
for (const entryName of projectAssets.archiveEntries) {
|
|
256
|
+
if (entryName === "project.json") {
|
|
257
|
+
archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\n`);
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
const contents = projectAssets.assetContents.get(entryName);
|
|
261
|
+
assert(contents, `Archive entry has no contents: ${entryName}`);
|
|
262
|
+
archiveEntries[entryName] = contents;
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
archive: zipSync(archiveEntries, {
|
|
266
|
+
level: 6,
|
|
267
|
+
mtime: fixedZipTimestamp
|
|
268
|
+
}),
|
|
269
|
+
assetCount: projectAssets.assetContents.size,
|
|
270
|
+
assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,
|
|
271
|
+
blockCleanUp,
|
|
272
|
+
bundlePlans: bundled.bundlePlans,
|
|
273
|
+
embeddedExtensionCount: bundled.extensions.length,
|
|
274
|
+
entryCount: projectAssets.archiveEntries.length,
|
|
275
|
+
projectAssetAdditions: projectAssets.summary,
|
|
276
|
+
source
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
//#endregion
|
|
280
|
+
export { createDeterministicSb3, fixedZipTimestamp, inspectSb3SourceForExtensionSync, sourceFormatVersion, validateSb3Source };
|
|
281
|
+
|
|
282
|
+
//# sourceMappingURL=source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"source.js","names":[],"sources":["../src/source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readdir, readFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strToU8, zipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {buildExtensionBundles, validateExtensionBundleConfigurations} from './extension-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n validateExtensionSourceMetadata,\n validateManagedExtensionContents,\n} from './extension-dependencies';\nimport {applyProjectAssetAdditions} from './project-asset-additions';\nimport type {ProjectAssetAdditionsSummary} from './project-asset-additions';\nimport {cleanUpTurboWarpBlocks} from './turbowarp-clean-up';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectAssetReference,\n ProjectJson,\n Sb3SourceManifest,\n UnknownRecord,\n} from './types';\n\nexport const sourceFormatVersion = 1;\nexport const fixedZipTimestamp = new Date(1980, 0, 1, 0, 0, 0, 0);\n\nexport interface InspectedSb3Source {\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n extensions: EmbeddedExtension[];\n extensionApiManifestContents: Map<string, Uint8Array>;\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n project: ProjectJson;\n resolvedSourceDirectory: string;\n sourceManifest: Sb3SourceManifest;\n}\n\nexport interface BlockCleanUpSummary {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n targetCount: number;\n}\n\nexport interface DeterministicSb3Options {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n projectAssetsPath?: string;\n}\n\nexport interface DeterministicSb3 {\n archive: Uint8Array;\n assetCount: number;\n assetReferenceCount: number;\n blockCleanUp: BlockCleanUpSummary | null;\n bundlePlans: ExtensionBundlePlan[];\n embeddedExtensionCount: number;\n entryCount: number;\n projectAssetAdditions: Readonly<ProjectAssetAdditionsSummary> | null;\n source: InspectedSb3Source;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function readJson(filePath: string, description: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(filePath, 'utf8'));\n } catch (error) {\n throw new Error(`${description} is not valid JSON: ${filePath} (${errorMessage(error)})`, {\n cause: error,\n });\n }\n}\n\nasync function assertDirectory(directoryPath: string, description: string): Promise<void> {\n const stats = await lstat(directoryPath);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `${description} must be a directory, not a file or symbolic link: ${directoryPath}`,\n );\n}\n\nasync function listRegularFiles(rootDirectory: string, description: string): Promise<string[]> {\n await assertDirectory(rootDirectory, description);\n const files: string[] = [];\n\n async function visit(directory: string, relativeDirectory: string): Promise<void> {\n const entries = await readdir(directory, {withFileTypes: true});\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n for (const entry of entries) {\n const relativePath = relativeDirectory\n ? path.posix.join(relativeDirectory, entry.name)\n : entry.name;\n const absolutePath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n await visit(absolutePath, relativePath);\n } else {\n assert(\n entry.isFile(),\n `${description} contains a symbolic link or unsupported entry: ${relativePath}`,\n );\n files.push(relativePath);\n }\n }\n }\n\n await visit(rootDirectory, '');\n return files;\n}\n\nfunction assertSameFileSet(\n actualFiles: string[],\n expectedFiles: string[],\n description: string,\n): void {\n const actual = new Set(actualFiles);\n const expected = new Set(expectedFiles);\n const missing = [...expected].filter((filePath) => !actual.has(filePath)).sort();\n const extra = [...actual].filter((filePath) => !expected.has(filePath)).sort();\n assert(\n missing.length === 0 && extra.length === 0,\n `${description} does not match its manifest. Missing: ${missing.join(', ') || '(none)'}. ` +\n `Extra: ${extra.join(', ') || '(none)'}.`,\n );\n}\n\nfunction md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\n}\n\nfunction validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest {\n assert(isObject(manifest), 'sb3-source.json must contain an object.');\n assert(\n manifest.formatVersion === sourceFormatVersion,\n `Unsupported SB3 source format version: ${manifest.formatVersion}`,\n );\n assert(\n manifest.project === 'project.source.json',\n 'SB3 source format 1 requires project.source.json.',\n );\n assert(\n manifest.embeddedExtensions === 'embedded-extensions.json',\n 'SB3 source format 1 requires embedded-extensions.json.',\n );\n assert(\n manifest.assetsDirectory === 'assets',\n 'SB3 source format 1 requires the assets directory.',\n );\n assert(\n Array.isArray(manifest.archiveEntries) && manifest.archiveEntries.length > 0,\n 'sb3-source.json archiveEntries must be a non-empty array.',\n );\n\n const seenEntries = new Set<string>();\n let projectEntryCount = 0;\n for (const rawEntryName of manifest.archiveEntries as unknown[]) {\n const entryName = validateArchiveEntryName(rawEntryName);\n assert(!seenEntries.has(entryName), `Duplicate archive entry in manifest: ${entryName}`);\n assert(\n !entryName.endsWith('/'),\n `Directory ZIP entries are not supported in SB3 source format 1: ${entryName}`,\n );\n assert(\n !/^(?:0|[1-9][0-9]*)$/u.test(entryName),\n `Integer-like ZIP entry names cannot preserve JavaScript object order: ${entryName}`,\n );\n seenEntries.add(entryName);\n if (entryName === 'project.json') {\n projectEntryCount += 1;\n }\n }\n assert(projectEntryCount === 1, 'archiveEntries must contain project.json exactly once.');\n}\n\nfunction validateExtensionManifest(\n extensionManifest: unknown,\n project: ProjectJson,\n extensionFiles: string[],\n): {extensionBundles: ExtensionBundleConfiguration[]; extensions: EmbeddedExtension[]} {\n assert(isObject(extensionManifest), 'embedded-extensions.json must contain an object.');\n assert(\n extensionManifest.formatVersion === sourceFormatVersion,\n `Unsupported embedded extension manifest version: ${extensionManifest.formatVersion}`,\n );\n assert(\n Array.isArray(extensionManifest.extensions),\n 'embedded-extensions.json extensions must be an array.',\n );\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n assert(\n isObject(extensionUrls),\n 'project.source.json extensionURLs must be an object when present.',\n );\n const extensionsById = new Map<string, EmbeddedExtension>();\n const expectedFiles: string[] = [];\n const extensions: EmbeddedExtension[] = [];\n\n for (const entry of extensionManifest.extensions as unknown[]) {\n assert(isObject(entry), 'Each embedded extension manifest entry must be an object.');\n const extension = entry as unknown as EmbeddedExtension;\n assert(\n typeof extension.id === 'string' && /^[A-Za-z0-9._-]+$/u.test(extension.id),\n `Invalid embedded extension ID: ${JSON.stringify(extension.id)}`,\n );\n assert(!extensionsById.has(extension.id), `Duplicate embedded extension ID: ${extension.id}`);\n const expectedPath = `extensions/${extension.id}.js`;\n assert(\n extension.path === expectedPath,\n `Embedded extension path must match its ID: expected ${expectedPath}, got ${extension.path}`,\n );\n assert(\n typeof extension.mediaType === 'string' &&\n extension.mediaType.length > 0 &&\n !/[;,\\r\\n]/u.test(extension.mediaType),\n `Invalid media type for embedded extension ${extension.id}: ${extension.mediaType}`,\n );\n assert(\n Array.isArray(extension.parameters) &&\n extension.parameters.every(\n (parameter) =>\n typeof parameter === 'string' && parameter.length > 0 && !/[;,\\r\\n]/u.test(parameter),\n ),\n `Invalid data URL parameters for embedded extension ${extension.id}.`,\n );\n assert(\n extension.encoding === 'base64' || extension.encoding === 'percent',\n `Unsupported encoding for embedded extension ${extension.id}: ${extension.encoding}`,\n );\n assert(\n extensionUrls[extension.id] === `embedded-extension:${extension.path}`,\n `project.source.json mapping does not match embedded extension ${extension.id}.`,\n );\n validateExtensionSourceMetadata(extension);\n extensionsById.set(extension.id, extension);\n extensions.push(extension);\n expectedFiles.push(`${extension.id}.js`);\n if (extension.source?.apiManifest) {\n expectedFiles.push(path.posix.relative('extensions', extension.source.apiManifest.path));\n }\n }\n\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n assert(\n typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:'),\n `project.source.json still contains an embedded data URL: ${extensionId}`,\n );\n if (typeof extensionUrl === 'string' && extensionUrl.startsWith('embedded-extension:')) {\n assert(\n extensionsById.has(extensionId),\n `project.source.json has no metadata for embedded extension ${extensionId}.`,\n );\n }\n }\n\n assertSameFileSet(extensionFiles, expectedFiles, 'Embedded extension files');\n return {\n extensionBundles: validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensions,\n ),\n extensions,\n };\n}\n\nfunction collectAssetReferences(\n project: ProjectJson,\n): {asset: ProjectAssetReference; description: string}[] {\n assert(Array.isArray(project.targets), 'project.source.json targets must be an array.');\n const references: {asset: ProjectAssetReference; description: string}[] = [];\n for (const [targetIndex, target] of (project.targets as unknown[]).entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n for (const [collectionName, kind] of [\n ['costumes', 'costume'],\n ['sounds', 'sound'],\n ] as const) {\n const assets: unknown = target[collectionName] ?? [];\n assert(\n Array.isArray(assets),\n `Project target ${targetIndex} ${collectionName} must be an array.`,\n );\n for (const [assetIndex, asset] of (assets as unknown[]).entries()) {\n assert(isObject(asset), `Project ${kind} ${targetIndex}:${assetIndex} must be an object.`);\n references.push({asset, description: `${kind} ${targetIndex}:${assetIndex}`});\n }\n }\n }\n return references;\n}\n\nfunction percentEncode(contents: Uint8Array): string {\n return [...contents]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction encodeExtensionDataUrl(extension: EmbeddedExtension, contents: Uint8Array): string {\n const metadata = [extension.mediaType, ...extension.parameters].join(';');\n if (extension.encoding === 'base64') {\n return `data:${metadata};base64,${Buffer.from(contents).toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(contents)}`;\n}\n\nasync function inspectSb3Source(\n sourceDirectory: string,\n validateManagedExtensions: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n await assertDirectory(resolvedSourceDirectory, 'SB3 source');\n const sourceManifest = await readJson(\n path.join(resolvedSourceDirectory, 'sb3-source.json'),\n 'SB3 source manifest',\n );\n validateSourceManifest(sourceManifest);\n const assetEntries = sourceManifest.archiveEntries.filter(\n (entryName) => entryName !== 'project.json',\n );\n const project: unknown = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.project),\n 'SB3 project source',\n );\n assert(isObject(project), 'project.source.json must contain an object.');\n const extensionManifest = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions),\n 'Embedded extension manifest',\n );\n\n const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);\n const extensionsDirectory = path.join(resolvedSourceDirectory, 'extensions');\n const [assetFiles, extensionFiles] = await Promise.all([\n listRegularFiles(assetsDirectory, 'Assets directory'),\n listRegularFiles(extensionsDirectory, 'Extensions directory'),\n ]);\n assertSameFileSet(assetFiles, assetEntries, 'Asset files');\n const {extensionBundles, extensions} = validateExtensionManifest(\n extensionManifest,\n project,\n extensionFiles,\n );\n\n const assetContents = new Map<string, Uint8Array>();\n await Promise.all(\n assetFiles.map(async (assetPath) => {\n assetContents.set(assetPath, await readFile(path.join(assetsDirectory, assetPath)));\n }),\n );\n const referencedAssets = new Set<string>();\n const references = collectAssetReferences(project);\n for (const {asset, description} of references) {\n assert(\n typeof asset.assetId === 'string' && /^[a-f0-9]{32}$/u.test(asset.assetId),\n `Invalid assetId for ${description}: ${asset.assetId}`,\n );\n assert(\n typeof asset.dataFormat === 'string' && /^[A-Za-z0-9]+$/u.test(asset.dataFormat),\n `Invalid dataFormat for ${description}: ${asset.dataFormat}`,\n );\n const expectedFilename = `${asset.assetId}.${asset.dataFormat}`;\n assert(\n asset.md5ext === expectedFilename,\n `Asset filename mismatch for ${description}: expected ${expectedFilename}, got ${asset.md5ext}`,\n );\n const contents = assetContents.get(expectedFilename);\n assert(contents, `Referenced asset is missing for ${description}: ${expectedFilename}`);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === asset.assetId,\n `Asset content hash mismatch for ${description}: expected ${asset.assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(expectedFilename);\n }\n const unreferencedAssets = assetFiles.filter((assetPath) => !referencedAssets.has(assetPath));\n assert(\n unreferencedAssets.length === 0,\n `Asset manifest contains unreferenced files: ${unreferencedAssets.join(', ')}`,\n );\n\n const extensionContents = new Map<string, Uint8Array>();\n const extensionApiManifestContents = new Map<string, Uint8Array>();\n await Promise.all(\n extensions.map(async (extension) => {\n const contents = await readFile(path.join(resolvedSourceDirectory, extension.path));\n if (validateManagedExtensions) {\n validateManagedExtensionContents(extension, contents);\n }\n extensionContents.set(extension.id, contents);\n if (extension.source?.apiManifest) {\n const apiManifestContents = await readFile(\n path.join(resolvedSourceDirectory, extension.source.apiManifest.path),\n );\n if (validateManagedExtensions) {\n validateManagedExtensionApiManifest(extension, apiManifestContents);\n }\n extensionApiManifestContents.set(extension.id, apiManifestContents);\n }\n }),\n );\n\n return {\n assetContents,\n assetReferenceCount: references.length,\n extensions,\n extensionApiManifestContents,\n extensionBundles,\n extensionContents,\n project,\n resolvedSourceDirectory,\n sourceManifest,\n };\n}\n\nexport async function inspectSb3SourceForExtensionSync(\n sourceDirectory: string,\n): Promise<InspectedSb3Source> {\n return inspectSb3Source(sourceDirectory, false);\n}\n\nexport async function validateSb3Source(sourceDirectory: string): Promise<InspectedSb3Source> {\n const source = await inspectSb3Source(sourceDirectory, true);\n buildExtensionBundles({\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n return source;\n}\n\nexport async function createDeterministicSb3(\n sourceDirectory: string,\n options: DeterministicSb3Options = {},\n): Promise<DeterministicSb3> {\n const {allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath} = options;\n assert(typeof cleanUpBlocks === 'boolean', 'cleanUpBlocks must be a boolean.');\n assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');\n assert(\n projectAssetsPath === undefined || typeof projectAssetsPath === 'string',\n 'projectAssetsPath must be a string when provided.',\n );\n const source = await validateSb3Source(sourceDirectory);\n const projectAssets: {\n archiveEntries: string[];\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n project: ProjectJson;\n summary: Readonly<ProjectAssetAdditionsSummary> | null;\n } = projectAssetsPath\n ? await applyProjectAssetAdditions({\n allowedAssetRoots,\n assetContents: source.assetContents,\n archiveEntries: source.sourceManifest.archiveEntries,\n manifestPath: projectAssetsPath,\n project: source.project,\n })\n : {\n archiveEntries: source.sourceManifest.archiveEntries,\n assetContents: source.assetContents,\n assetReferenceCount: 0,\n project: source.project,\n summary: null,\n };\n const bundled = buildExtensionBundles({\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: projectAssets.project,\n });\n let project = structuredClone(bundled.project);\n let blockCleanUp: BlockCleanUpSummary | null = null;\n if (cleanUpBlocks) {\n const cleaned = cleanUpTurboWarpBlocks(project);\n project = cleaned.project;\n blockCleanUp = {\n movedCommentCount: cleaned.movedCommentCount,\n movedScriptCount: cleaned.movedScriptCount,\n scriptCount: cleaned.scriptCount,\n targetCount: cleaned.targetCount,\n };\n }\n const extensionUrls: Record<string, unknown> = project.extensionURLs ?? {};\n for (const extension of bundled.extensions) {\n const contents = bundled.extensionContents.get(extension.id);\n assert(contents, `Embedded extension has no contents: ${extension.id}`);\n extensionUrls[extension.id] = encodeExtensionDataUrl(extension, contents);\n }\n project.extensionURLs = extensionUrls;\n\n const archiveEntries: Record<string, Uint8Array> = {};\n for (const entryName of projectAssets.archiveEntries) {\n if (entryName === 'project.json') {\n archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\\n`);\n continue;\n }\n const contents = projectAssets.assetContents.get(entryName);\n assert(contents, `Archive entry has no contents: ${entryName}`);\n archiveEntries[entryName] = contents;\n }\n const archive = zipSync(archiveEntries, {\n level: 6,\n mtime: fixedZipTimestamp,\n });\n\n return {\n archive,\n assetCount: projectAssets.assetContents.size,\n assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,\n blockCleanUp,\n bundlePlans: bundled.bundlePlans,\n embeddedExtensionCount: bundled.extensions.length,\n entryCount: projectAssets.archiveEntries.length,\n projectAssetAdditions: projectAssets.summary,\n source,\n };\n}\n"],"mappings":";;;;;;;;;;;;AA6BA,IAAa,sBAAsB;AACnC,IAAa,oBAAoB,IAAI,KAAK,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AAuChE,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,eAAe,SAAS,UAAkB,aAAuC;CAC/E,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,UAAU,MAAM,CAAC;CACpD,SAAS,OAAO;EACd,MAAM,IAAI,MAAM,GAAG,YAAY,sBAAsB,SAAS,IAAI,aAAa,KAAK,EAAE,IAAI,EACxF,OAAO,MACT,CAAC;CACH;AACF;AAEA,eAAe,gBAAgB,eAAuB,aAAoC;CACxF,MAAM,QAAQ,MAAM,MAAM,aAAa;CACvC,OACE,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,GAC7C,GAAG,YAAY,qDAAqD,eACtE;AACF;AAEA,eAAe,iBAAiB,eAAuB,aAAwC;CAC7F,MAAM,gBAAgB,eAAe,WAAW;CAChD,MAAM,QAAkB,CAAC;CAEzB,eAAe,M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AAS;EAC1D,OAAO,UAAU,kCAAkC,WAAW;EAC9D,eAAe,aAAa;CAC9B;CAMA,OAAO;EACL,SANc,QAAQ,gBAAgB;GACtC,OAAO;GACP,OAAO;EACT,CAGE;EACA,YAAY,cAAc,cAAc;EACxC,qBAAqB,OAAO,sBAAsB,cAAc;EAChE;EACA,aAAa,QAAQ;EACrB,wBAAwB,QAAQ,WAAW;EAC3C,YAAY,cAAc,eAAe;EACzC,uBAAuB,cAAc;EACrC;CACF;AACF"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { ProjectJson } from './types';
|
|
2
|
+
export declare const turboWarpCleanUpLayout: Readonly<{
|
|
3
|
+
columnGap: 96;
|
|
4
|
+
columnTolerance: 256;
|
|
5
|
+
rowGap: 72;
|
|
6
|
+
startX: 48;
|
|
7
|
+
startY: 64;
|
|
8
|
+
}>;
|
|
9
|
+
export interface TargetCleanUpResult {
|
|
10
|
+
movedCommentCount: number;
|
|
11
|
+
movedScriptCount: number;
|
|
12
|
+
scriptCount: number;
|
|
13
|
+
}
|
|
14
|
+
export interface TurboWarpCleanUpResult extends TargetCleanUpResult {
|
|
15
|
+
project: ProjectJson;
|
|
16
|
+
targetCount: number;
|
|
17
|
+
}
|
|
18
|
+
export declare function cleanUpTurboWarpBlocks(project: ProjectJson): TurboWarpCleanUpResult;
|