@tanqory/partner-cli 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/bin/tanqory-partner.mjs +10 -0
  3. package/config/mirror-allowlist.json +17 -0
  4. package/config/theme-licences.json +108 -0
  5. package/config/third-party-toolchains.json +45 -0
  6. package/lib/api.mjs +109 -0
  7. package/lib/auth.mjs +211 -0
  8. package/lib/check.mjs +63 -0
  9. package/lib/cli.mjs +217 -0
  10. package/lib/mcp.mjs +177 -0
  11. package/lib/ops.mjs +179 -0
  12. package/lib/theme.mjs +121 -0
  13. package/lib/vendor/partner-checks.cjs +1617 -0
  14. package/package.json +59 -4
  15. package/starter/LICENSE +18 -0
  16. package/starter/README.md +38 -0
  17. package/starter/config/settings.json +3 -0
  18. package/starter/gitignore +3 -0
  19. package/starter/locales/en.json +22 -0
  20. package/starter/locales/th.json +22 -0
  21. package/starter/package.json +29 -0
  22. package/starter/regions/footer.json +35 -0
  23. package/starter/regions/header.json +13 -0
  24. package/starter/scripts/build.mjs +195 -0
  25. package/starter/scripts/probe.ts +4 -0
  26. package/starter/src/bundle.ts +15 -0
  27. package/starter/src/components/parts.tsx +32 -0
  28. package/starter/src/entry.client.tsx +6 -0
  29. package/starter/src/entry.server.tsx +13 -0
  30. package/starter/src/sections/chrome.tsx +132 -0
  31. package/starter/src/sections/commerce.tsx +242 -0
  32. package/starter/src/sections/content.tsx +111 -0
  33. package/starter/src/sections/editorial.tsx +107 -0
  34. package/starter/src/settings.ts +15 -0
  35. package/starter/src/styles/theme.css +224 -0
  36. package/starter/src/templates.ts +14 -0
  37. package/starter/src/theme.tsx +76 -0
  38. package/starter/templates/404.json +14 -0
  39. package/starter/templates/account.json +14 -0
  40. package/starter/templates/article.json +14 -0
  41. package/starter/templates/blog.json +14 -0
  42. package/starter/templates/cart.json +14 -0
  43. package/starter/templates/collection.json +14 -0
  44. package/starter/templates/index.json +36 -0
  45. package/starter/templates/page.contact.json +18 -0
  46. package/starter/templates/page.json +14 -0
  47. package/starter/templates/product.json +18 -0
  48. package/starter/templates/search.json +14 -0
  49. package/starter/tsconfig.json +17 -0
  50. package/starter/vite.client.config.ts +17 -0
  51. package/starter/vite.probe.config.ts +16 -0
  52. package/starter/vite.server.config.ts +32 -0
  53. package/README.md +0 -3
@@ -0,0 +1,1617 @@
1
+ // GENERATED by scripts/prepare.mjs from apps/build-service/src/review/partner-source.ts. Do not edit.
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // ../../apps/build-service/src/review/partner-source.ts
32
+ var partner_source_exports = {};
33
+ __export(partner_source_exports, {
34
+ checkPartnerSource: () => checkPartnerSource
35
+ });
36
+ module.exports = __toCommonJS(partner_source_exports);
37
+ var import_node_fs4 = require("node:fs");
38
+ var import_node_path4 = require("node:path");
39
+ var import_node_stream = require("node:stream");
40
+ var import_theme_abi2 = require("@tanqory/theme-abi");
41
+
42
+ // ../../apps/build-service/src/artifact/digest.ts
43
+ var import_node_crypto = require("node:crypto");
44
+ var SHA256_HEX_RE = /^[0-9a-f]{64}$/;
45
+ function sha256Hex(bytes) {
46
+ return (0, import_node_crypto.createHash)("sha256").update(bytes).digest("hex");
47
+ }
48
+ function sha256Digest(bytes) {
49
+ return `sha256:${sha256Hex(bytes)}`;
50
+ }
51
+
52
+ // ../../apps/build-service/src/artifact/sbom.ts
53
+ var import_yaml = require("yaml");
54
+
55
+ // ../../apps/build-service/src/artifact/canonical-json.ts
56
+ var jcs = require("@tanqory/theme-abi/jcs");
57
+ var CanonicalJsonError = jcs.CanonicalJsonError;
58
+ var CANONICAL_JSON_MAX_DEPTH = jcs.CANONICAL_JSON_MAX_DEPTH;
59
+ function canonicalize(value) {
60
+ return jcs.canonicalJson(value);
61
+ }
62
+ function canonicalJsonFile(value) {
63
+ return Buffer.from(canonicalize(value) + "\n", "utf8");
64
+ }
65
+
66
+ // ../../apps/build-service/src/artifact/sbom.ts
67
+ var CYCLONEDX_SPEC_VERSION = "1.6";
68
+ var LockfileParseError = class extends Error {
69
+ constructor() {
70
+ super(...arguments);
71
+ this.name = "LockfileParseError";
72
+ }
73
+ };
74
+ function splitPackageKey(key) {
75
+ const at = key.lastIndexOf("@");
76
+ if (at <= 0) throw new LockfileParseError(`unparseable package key: ${key}`);
77
+ return { name: key.slice(0, at), version: key.slice(at + 1) };
78
+ }
79
+ function parsePnpmLockfile(bytes) {
80
+ let doc;
81
+ try {
82
+ doc = (0, import_yaml.parse)(Buffer.from(bytes).toString("utf8"));
83
+ } catch (e) {
84
+ throw new LockfileParseError(`pnpm-lock.yaml is not valid YAML: ${e.message}`);
85
+ }
86
+ if (!doc || typeof doc !== "object")
87
+ throw new LockfileParseError("pnpm-lock.yaml is not a mapping");
88
+ const root = doc;
89
+ const lockfileVersion = String(root["lockfileVersion"] ?? "");
90
+ if (!lockfileVersion) throw new LockfileParseError("pnpm-lock.yaml has no lockfileVersion");
91
+ const packages = [];
92
+ const rawPackages = root["packages"] ?? {};
93
+ for (const [key, entry] of Object.entries(rawPackages)) {
94
+ const { name, version } = splitPackageKey(key);
95
+ const resolution = entry?.["resolution"] ?? {};
96
+ packages.push({
97
+ name,
98
+ version,
99
+ ...typeof resolution["integrity"] === "string" ? { integrity: resolution["integrity"] } : {},
100
+ ...typeof resolution["tarball"] === "string" ? { tarball: resolution["tarball"] } : {}
101
+ });
102
+ }
103
+ const rootDependencies = {};
104
+ const importers = root["importers"] ?? {};
105
+ const importer = importers["."] ?? {};
106
+ for (const section of ["dependencies", "optionalDependencies", "devDependencies"]) {
107
+ const deps = importer[section] ?? {};
108
+ for (const [name, spec] of Object.entries(deps)) {
109
+ rootDependencies[name] = typeof spec === "string" ? spec : String(spec.version ?? "");
110
+ }
111
+ }
112
+ const importerDependencies = [];
113
+ for (const [importerName, imp] of Object.entries(importers)) {
114
+ for (const section of [
115
+ "dependencies",
116
+ "optionalDependencies",
117
+ "devDependencies",
118
+ "peerDependencies"
119
+ ]) {
120
+ const deps = (imp ?? {})[section] ?? {};
121
+ for (const [name, spec] of Object.entries(deps))
122
+ importerDependencies.push({
123
+ importer: importerName,
124
+ section,
125
+ name,
126
+ specifier: typeof spec === "string" ? "" : String(spec?.specifier ?? ""),
127
+ version: typeof spec === "string" ? spec : String(spec?.version ?? "")
128
+ });
129
+ }
130
+ }
131
+ const snapshots = [];
132
+ const rawSnapshots = root["snapshots"] ?? {};
133
+ for (const [key, entry] of Object.entries(rawSnapshots)) {
134
+ const dependencies = [];
135
+ for (const section of ["dependencies", "optionalDependencies"]) {
136
+ const deps = (entry ?? {})[section] ?? {};
137
+ for (const [name, version] of Object.entries(deps))
138
+ dependencies.push({ name, version: String(version) });
139
+ }
140
+ snapshots.push({ key, dependencies });
141
+ }
142
+ packages.sort((a, b) => (a.name + "@" + a.version).localeCompare(b.name + "@" + b.version));
143
+ return { lockfileVersion, packages, rootDependencies, importerDependencies, snapshots };
144
+ }
145
+ var INTEGRITY_ALG = {
146
+ sha512: "SHA-512",
147
+ sha384: "SHA-384",
148
+ sha256: "SHA-256",
149
+ sha1: "SHA-1"
150
+ };
151
+ function integrityToHash(integrity) {
152
+ const dash = integrity.indexOf("-");
153
+ if (dash < 0) return void 0;
154
+ const alg = INTEGRITY_ALG[integrity.slice(0, dash)];
155
+ if (!alg) return void 0;
156
+ return { alg, content: Buffer.from(integrity.slice(dash + 1), "base64").toString("hex") };
157
+ }
158
+ function purlOf(name, version) {
159
+ if (name.startsWith("@")) {
160
+ const slash = name.indexOf("/");
161
+ return `pkg:npm/${encodeURIComponent(name.slice(1, slash))}/${name.slice(slash + 1)}@${version}`;
162
+ }
163
+ return `pkg:npm/${name}@${version}`;
164
+ }
165
+ function buildCycloneDxSbom(input) {
166
+ const components = input.lockfile.packages.map((p) => {
167
+ const hash = p.integrity ? integrityToHash(p.integrity) : void 0;
168
+ return {
169
+ type: "library",
170
+ name: p.name,
171
+ version: p.version,
172
+ purl: purlOf(p.name, p.version),
173
+ "bom-ref": purlOf(p.name, p.version),
174
+ ...hash ? { hashes: [hash] } : {}
175
+ };
176
+ }).sort((a, b) => a.purl < b.purl ? -1 : a.purl > b.purl ? 1 : 0);
177
+ const direct = Object.entries(input.lockfile.rootDependencies).map(([name, version]) => purlOf(name, version)).sort();
178
+ return {
179
+ bomFormat: "CycloneDX",
180
+ specVersion: CYCLONEDX_SPEC_VERSION,
181
+ version: 1,
182
+ metadata: {
183
+ component: {
184
+ type: "application",
185
+ name: input.themeName,
186
+ version: input.themeVersion,
187
+ "bom-ref": "theme",
188
+ properties: [
189
+ { name: "tq:inputDigest", value: input.inputDigest },
190
+ { name: "tq:sourceDigest", value: input.sourceDigest }
191
+ ]
192
+ }
193
+ },
194
+ components,
195
+ dependencies: [{ ref: "theme", dependsOn: direct }]
196
+ };
197
+ }
198
+ function serializeSbom(input) {
199
+ return canonicalJsonFile(buildCycloneDxSbom(input));
200
+ }
201
+
202
+ // shim:api-core-shim
203
+ var ApiException = class extends Error {
204
+ constructor(errorCode, options = {}) {
205
+ super(options.message || String(errorCode));
206
+ this.errorCode = String(errorCode).toLowerCase().replace(/\s+/g, "_");
207
+ this.httpStatus = options.httpStatus ?? 500;
208
+ this.param = options.param;
209
+ this.details = options.details;
210
+ }
211
+ getStatus() {
212
+ return this.httpStatus;
213
+ }
214
+ };
215
+
216
+ // ../../apps/build-service/src/common/errors/build-service-errors.ts
217
+ var BuildServiceError = class extends ApiException {
218
+ constructor(type, code, status, message, details) {
219
+ super(code, { message, httpStatus: status, ...details ? { details: { ...details } } : {} });
220
+ this.name = "BuildServiceError";
221
+ const body = this.getResponse();
222
+ body.error.type = type;
223
+ this.errorType = type;
224
+ this.message = message;
225
+ }
226
+ };
227
+ var IngestRejectedError = class extends BuildServiceError {
228
+ constructor(kind, message, path, extra, code = "ingest_rejected") {
229
+ super("invalid_request_error", code, 422, message, {
230
+ kind,
231
+ ...path !== void 0 ? { path } : {},
232
+ ...extra
233
+ });
234
+ this.kind = kind;
235
+ this.path = path;
236
+ this.name = "IngestRejectedError";
237
+ }
238
+ };
239
+ var PathCollisionError = class extends IngestRejectedError {
240
+ constructor(message, paths) {
241
+ super(
242
+ "params",
243
+ message,
244
+ paths[1],
245
+ { paths: [...paths], collidesWith: paths[0] },
246
+ "path_collision"
247
+ );
248
+ this.paths = paths;
249
+ this.name = "PathCollisionError";
250
+ }
251
+ };
252
+ var UnsafeArchiveError = class extends IngestRejectedError {
253
+ constructor(message, path) {
254
+ super("archive", message, path);
255
+ this.name = "UnsafeArchiveError";
256
+ }
257
+ };
258
+
259
+ // ../../apps/build-service/src/config/mirror-allowlist.ts
260
+ var import_node_fs = require("node:fs");
261
+ var import_node_path = require("node:path");
262
+ var NAME_RE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
263
+ var VERSION_RE = /^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/;
264
+ var RANGE_RE = /^([\^~]?)((?:0|[1-9]\d{0,8})\.(?:0|[1-9]\d{0,8})\.(?:0|[1-9]\d{0,8}))$/;
265
+ var INTEGRITY_RE = /^sha512-[A-Za-z0-9+/]{86}==$/;
266
+ function parseExactVersion(version) {
267
+ const m = VERSION_RE.exec(version);
268
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
269
+ }
270
+ var compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
271
+ function versionSatisfies(version, range) {
272
+ const v = parseExactVersion(version);
273
+ const r = RANGE_RE.exec(range);
274
+ if (!v || !r) return false;
275
+ const base = parseExactVersion(r[2]);
276
+ if (compare(v, base) < 0) return false;
277
+ switch (r[1]) {
278
+ case "":
279
+ return compare(v, base) === 0;
280
+ case "~":
281
+ return v[0] === base[0] && v[1] === base[1];
282
+ default:
283
+ if (base[0] > 0) return v[0] === base[0];
284
+ if (base[1] > 0) return v[0] === 0 && v[1] === base[1];
285
+ return compare(v, base) === 0;
286
+ }
287
+ }
288
+ function parseMirrorAllowlist(raw, where = "mirror allowlist") {
289
+ const fail = (message) => {
290
+ throw new Error(`${where}: ${message}`);
291
+ };
292
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
293
+ if (!isRecord(raw)) return fail("the file must be a JSON object");
294
+ for (const key of Object.keys(raw))
295
+ if (key !== "$comment" && key !== "packages") fail(`unknown member ${JSON.stringify(key)}`);
296
+ const list = raw["packages"];
297
+ if (!isRecord(list))
298
+ return fail(
299
+ '"packages" must be an object of name \u2192 { range, versions } (names alone pin nothing)'
300
+ );
301
+ const packages = /* @__PURE__ */ new Map();
302
+ for (const [name, entry] of Object.entries(list)) {
303
+ const at = `packages[${JSON.stringify(name)}]`;
304
+ if (!NAME_RE.test(name)) fail(`${at}: not a package name`);
305
+ if (!isRecord(entry)) return fail(`${at} must be { range, versions }`);
306
+ for (const key of Object.keys(entry))
307
+ if (key !== "range" && key !== "versions")
308
+ fail(`${at}: unknown member ${JSON.stringify(key)}`);
309
+ const range = entry["range"];
310
+ if (typeof range !== "string" || !RANGE_RE.test(range))
311
+ return fail(`${at}.range must be X.Y.Z, ^X.Y.Z or ~X.Y.Z`);
312
+ const listed = entry["versions"];
313
+ if (!isRecord(listed) || Object.keys(listed).length === 0)
314
+ return fail(`${at}.versions must list at least one version with its integrity`);
315
+ const versions = /* @__PURE__ */ new Map();
316
+ for (const [version, integrity] of Object.entries(listed)) {
317
+ if (!parseExactVersion(version))
318
+ fail(`${at}.versions: ${JSON.stringify(version)} is not X.Y.Z`);
319
+ if (!versionSatisfies(version, range))
320
+ fail(`${at}.versions: ${version} does not satisfy the entry's range ${range}`);
321
+ if (typeof integrity !== "string" || !INTEGRITY_RE.test(integrity))
322
+ return fail(`${at}.versions[${version}] must be a sha512 integrity (sha512-<base64>)`);
323
+ versions.set(version, integrity);
324
+ }
325
+ packages.set(name, { range, versions });
326
+ }
327
+ return { packages };
328
+ }
329
+ function loadMirrorAllowlist(path = (0, import_node_path.join)(__dirname, "..", "..", "config", "mirror-allowlist.json")) {
330
+ return parseMirrorAllowlist(JSON.parse((0, import_node_fs.readFileSync)(path, "utf8")), `mirror allowlist ${path}`);
331
+ }
332
+ function allowlistProblem(allowlist, name, version, integrity) {
333
+ const entry = allowlist.packages.get(name);
334
+ if (!entry) return "is not on the mirror allowlist";
335
+ const pinned = entry.versions.get(version);
336
+ if (pinned === void 0)
337
+ return versionSatisfies(version, entry.range) ? `is within the allowlisted range ${entry.range} but that version has no pinned integrity (allowlisted: ${[...entry.versions.keys()].join(", ")})` : `is outside the allowlisted range ${entry.range}`;
338
+ if (!integrity) return "has no resolution.integrity";
339
+ if (integrity !== pinned)
340
+ return `has resolution.integrity ${integrity}, not the one pinned on the mirror allowlist for that version`;
341
+ return void 0;
342
+ }
343
+
344
+ // ../../apps/build-service/src/config/third-party.ts
345
+ var import_node_fs2 = require("node:fs");
346
+ var import_node_path2 = require("node:path");
347
+
348
+ // ../../apps/build-service/src/config/first-party-themes.ts
349
+ var FIRST_PARTY_THEMES = Object.freeze([
350
+ {
351
+ // Nova on Theme ABI v2: tanqory/tanqory-platform-onlinestore `themes/nova-v2` (draft PR #194).
352
+ // `themeId` is the installation's `theme_key` verbatim (site-release §1.3b, A12).
353
+ themeId: "nova",
354
+ visibility: "private",
355
+ owner: "target-store",
356
+ callers: ["platform-operator"],
357
+ gitUrls: [],
358
+ allowTarball: true
359
+ },
360
+ {
361
+ // Nova v3 — the redesigned Nova on Theme ABI v2: tanqory/tanqory-platform-onlinestore `themes/nova-v3`
362
+ // (branch feat/nova-v3). Its own theme key, so a store can install it beside the Nova it runs (its own
363
+ // Themes row, its own content line) and switch with Publish; rollback is the previous generation.
364
+ themeId: "nova-v3",
365
+ visibility: "private",
366
+ owner: "target-store",
367
+ // storefront-provisioner = central's provisioning of NEW stores (apps/api account/storefront-provisioning*.ts,
368
+ // OS-RT-9; was admin-api's): one private Nova V3 build per new store, from the tarball digest the provisioner
369
+ // holds as NOVA_V3_SOURCE_DIGEST.
370
+ callers: ["platform-operator", "storefront-provisioner"],
371
+ gitUrls: [],
372
+ allowTarball: true
373
+ }
374
+ ]);
375
+
376
+ // ../../apps/build-service/src/config/third-party.ts
377
+ var THIRD_PARTY_PLATFORM_PACKAGES = /* @__PURE__ */ new Map([
378
+ ["@tanqory/theme-kit", "runtime"],
379
+ ["@tanqory/theme-abi", "runtime"],
380
+ ["@tanqory/theme-conformance", "runtime"],
381
+ ["@tanqory/cli", "dev"],
382
+ ["@tanqory/dev-mcp", "dev"]
383
+ ]);
384
+ var EXACT_VERSION_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
385
+ var THIRD_PARTY_TOOLCHAINS_PATH = (0, import_node_path2.join)(
386
+ __dirname,
387
+ "..",
388
+ "..",
389
+ "config",
390
+ "third-party-toolchains.json"
391
+ );
392
+ function loadThirdPartyKits(path = THIRD_PARTY_TOOLCHAINS_PATH) {
393
+ const doc = JSON.parse((0, import_node_fs2.readFileSync)(path, "utf8"));
394
+ if (!Array.isArray(doc.kits) || doc.kits.length === 0)
395
+ throw new Error(`${path}: kits must be a non-empty list`);
396
+ const seen = /* @__PURE__ */ new Set();
397
+ return doc.kits.map((k) => {
398
+ if (typeof k.version !== "string" || !EXACT_VERSION_RE.test(k.version) || !k.version.startsWith("2."))
399
+ throw new Error(`${path}: ${JSON.stringify(k.version)} is not an exact 2.x version`);
400
+ if (seen.has(k.version)) throw new Error(`${path}: ${k.version} is listed twice`);
401
+ seen.add(k.version);
402
+ if ("pack" in k) {
403
+ if (k.pack !== `tanqory-theme-kit-${k.version}.tgz`)
404
+ throw new Error(`${path}: ${k.version} pack must be tanqory-theme-kit-${k.version}.tgz`);
405
+ if ("integrity" in k || "gitHead" in k)
406
+ throw new Error(`${path}: ${k.version} is a pack; it pins no registry gitHead or integrity`);
407
+ return { version: k.version, pack: `tanqory-theme-kit-${k.version}.tgz` };
408
+ }
409
+ if (typeof k.gitHead !== "string" || !/^[0-9a-f]{40}$/.test(k.gitHead))
410
+ throw new Error(`${path}: ${k.version} has no 40-hex gitHead`);
411
+ if (typeof k.integrity !== "string" || !/^sha512-[A-Za-z0-9+/]{86}==$/.test(k.integrity))
412
+ throw new Error(`${path}: ${k.version} has no sha512 integrity`);
413
+ return { version: k.version, gitHead: k.gitHead, integrity: k.integrity };
414
+ });
415
+ }
416
+ var STARTER_ABI_VERSION = "2.0";
417
+ var STARTER_DEFAULT_BUILDS = ["scripts/abi/build.mjs", "scripts/build.mjs"];
418
+ var STARTER_DEFAULT_OUT = "dist/abi";
419
+ var STARTER_PATH_RE = /^(?!\/)(?!.*(?:^|\/)\.\.?(?:\/|$))[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;
420
+ var STARTER_PROVIDED_PACKAGES = /* @__PURE__ */ new Set([
421
+ "react",
422
+ "react-dom",
423
+ "vite",
424
+ "@vitejs/plugin-react"
425
+ ]);
426
+ function isStarterDevTool(name) {
427
+ return /^(typescript|vitest|jsdom|axe-core|playwright|playwright-core)$/.test(name) || /^@types\/[a-z0-9._-]+$/.test(name) || /^@testing-library\/[a-z0-9._-]+$/.test(name);
428
+ }
429
+ function isStarterIgnoredPath(path) {
430
+ const first = path.split("/")[0];
431
+ return [
432
+ "tests",
433
+ ".github",
434
+ ".vscode",
435
+ ".claude",
436
+ ".codex",
437
+ ".gemini",
438
+ ".cursor",
439
+ ".git",
440
+ "node_modules",
441
+ "dist",
442
+ "reports",
443
+ "coverage"
444
+ ].includes(first) || // .tanqory/ holds theme inputs (e.g. the Nova fork's frozen contracts); only the dev server's state is dropped
445
+ path.startsWith(".tanqory/dev/") || [".mcp.json", "AGENTS.md", "CLAUDE.md", ".gitignore", "_gitignore", ".DS_Store"].includes(path);
446
+ }
447
+
448
+ // ../../apps/build-service/src/ingest/archive-guard.ts
449
+ var import_node_crypto3 = require("node:crypto");
450
+ var tar = __toESM(require("tar"));
451
+
452
+ // ../../apps/build-service/src/artifact/merkle.ts
453
+ var import_node_crypto2 = require("node:crypto");
454
+ var SOURCE_MERKLE_HEADER = "tanqory-theme-source/1\n";
455
+ function comparePathBytes(a, b) {
456
+ return Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
457
+ }
458
+ function sortLeaves(leaves) {
459
+ return [...leaves].sort((a, b) => comparePathBytes(a.path, b.path));
460
+ }
461
+ var MerkleListError = class extends Error {
462
+ constructor() {
463
+ super(...arguments);
464
+ this.name = "MerkleListError";
465
+ }
466
+ };
467
+ function merkleListPreimage(leaves, header) {
468
+ const sorted = sortLeaves(leaves);
469
+ const parts = [Buffer.from(header, "utf8")];
470
+ let previous;
471
+ for (const leaf of sorted) {
472
+ if (previous !== void 0 && previous === leaf.path) {
473
+ throw new MerkleListError(`duplicate path in Merkle list: ${leaf.path}`);
474
+ }
475
+ previous = leaf.path;
476
+ if (!SHA256_HEX_RE.test(leaf.sha256)) {
477
+ throw new MerkleListError(`leaf ${leaf.path}: sha256 must be 64 lowercase hex chars`);
478
+ }
479
+ if (!Number.isInteger(leaf.size) || leaf.size < 0) {
480
+ throw new MerkleListError(`leaf ${leaf.path}: size must be a non-negative integer`);
481
+ }
482
+ if (/[\s\0]/.test(leaf.path)) {
483
+ throw new MerkleListError(
484
+ `leaf path contains whitespace or NUL: ${JSON.stringify(leaf.path)}`
485
+ );
486
+ }
487
+ parts.push(Buffer.from(`${leaf.sha256} ${leaf.size} ${leaf.path}
488
+ `, "utf8"));
489
+ }
490
+ return Buffer.concat(parts);
491
+ }
492
+ function merkleListDigest(leaves, header) {
493
+ const hex = (0, import_node_crypto2.createHash)("sha256").update(merkleListPreimage(leaves, header)).digest("hex");
494
+ return `sha256:${hex}`;
495
+ }
496
+ var sourceDigestOf = (leaves) => merkleListDigest(leaves, SOURCE_MERKLE_HEADER);
497
+
498
+ // ../../apps/build-service/src/artifact/paths.ts
499
+ var MAX_PATH_BYTES = 200;
500
+ function relativePathProblem(path, opts = {}) {
501
+ if (path.length === 0) return "empty";
502
+ if (path.normalize("NFC") !== path) return "not_nfc";
503
+ if (Buffer.byteLength(path, "utf8") > MAX_PATH_BYTES) return "too_long";
504
+ if (path.startsWith("/")) return "absolute";
505
+ if (path.includes("\\")) return "backslash";
506
+ if (/[\u0000-\u001f\u007f]/.test(path)) return "control_char";
507
+ if (/\s/.test(path)) return "whitespace";
508
+ for (const segment of path.split("/")) {
509
+ if (segment === "") return "empty_segment";
510
+ if (segment === "." || segment === "..") return "dot_segment";
511
+ if (!opts.allowDotfiles && segment.startsWith(".")) return "dotfile";
512
+ }
513
+ return null;
514
+ }
515
+
516
+ // ../../apps/build-service/src/artifact/inline-scripts.ts
517
+ var INLINE_SCRIPT_SOURCE = /^src\/inline\/[^/]+\.js$/;
518
+ function inlineScriptProblem(bytes) {
519
+ const text = Buffer.from(bytes).toString("utf8");
520
+ if (!Buffer.from(text, "utf8").equals(Buffer.from(bytes)) || text.charCodeAt(0) === 65279)
521
+ return "must be valid UTF-8 without a BOM";
522
+ if (/<\/script/i.test(text))
523
+ return 'must not contain "</script" (it would end the inline script element early)';
524
+ if (text.includes("<!--")) return 'must not contain "<!--" (HTML script-data escape)';
525
+ return null;
526
+ }
527
+
528
+ // ../../apps/build-service/src/ingest/ingest-gate.ts
529
+ var import_theme_abi = require("@tanqory/theme-abi");
530
+
531
+ // ../../apps/build-service/src/artifact/files.ts
532
+ function leafOf(file) {
533
+ return { path: file.path, sha256: sha256Hex(file.bytes), size: file.bytes.byteLength };
534
+ }
535
+ function leavesOf(files) {
536
+ return sortLeaves(files.map(leafOf));
537
+ }
538
+
539
+ // ../../apps/build-service/src/ingest/ingest-gate.ts
540
+ var INGEST_LIMITS = Object.freeze({
541
+ maxEntries: 1e4,
542
+ maxUnpackedBytes: 64 * 1024 * 1024,
543
+ maxFileBytes: 8 * 1024 * 1024,
544
+ maxArchiveBytes: 100 * 1024 * 1024,
545
+ /** unpacked / compressed, checked once ≥ ratioCheckAfterBytes of archive have been read */
546
+ maxCompressionRatio: 100,
547
+ ratioCheckAfterBytes: 4 * 1024 * 1024
548
+ });
549
+ var DENY_BASENAMES = /* @__PURE__ */ new Set([".npmrc", ".pnpmfile.cjs", "pnpm-workspace.yaml"]);
550
+ var DENY_SEGMENTS = /* @__PURE__ */ new Set(["node_modules", ".git", ".github", ".husky"]);
551
+ var ALLOW_FILES = /* @__PURE__ */ new Set(["package.json", "pnpm-lock.yaml", "manifest.json"]);
552
+ var ALLOW_PREFIXES = [
553
+ "src/",
554
+ "sections/",
555
+ "templates/",
556
+ "layouts/",
557
+ "assets/",
558
+ "locales/",
559
+ "config/"
560
+ ];
561
+ var ALLOW_PATTERNS = [/^README[^/]*$/, /^LICENSE[^/]*$/];
562
+ var FLATTENED_PREFIXES = ["locales/", "config/templates/", "config/regions/"];
563
+ var TOOLCHAIN_EXACT = /* @__PURE__ */ new Set([
564
+ "vite",
565
+ "esbuild",
566
+ "rollup",
567
+ "react",
568
+ "react-dom",
569
+ "typescript",
570
+ "postcss",
571
+ "tailwindcss",
572
+ "lightningcss"
573
+ ]);
574
+ var TOOLCHAIN_PREFIXES = ["@vitejs/", "@rollup/", "@tanqory/theme-"];
575
+ var VITE_IMPORT_ALLOW = [/^vite$/, /^@tanqory\/vite-plugin-[a-z0-9-]+$/, /^node:(path|url)$/];
576
+ function isToolchainPackage(name) {
577
+ return TOOLCHAIN_EXACT.has(name) || TOOLCHAIN_PREFIXES.some((p) => name.startsWith(p));
578
+ }
579
+ var PLATFORM_PACKAGE_SECTIONS = {
580
+ runtime: ["dependencies", "devDependencies"],
581
+ dev: ["devDependencies"]
582
+ };
583
+ function basename(path) {
584
+ return path.slice(path.lastIndexOf("/") + 1);
585
+ }
586
+ function denyReason(path) {
587
+ const base = basename(path);
588
+ const segments = path.split("/");
589
+ for (const seg of segments) {
590
+ if (DENY_SEGMENTS.has(seg)) return `${seg}/ is not accepted`;
591
+ }
592
+ if (DENY_BASENAMES.has(base))
593
+ return `${base} is rejected (pnpm/npm configuration is platform-owned)`;
594
+ if (base.startsWith(".yarnrc"))
595
+ return `${base} is rejected (yarn configuration is platform-owned)`;
596
+ if (base.startsWith("Dockerfile")) return "Dockerfiles are rejected";
597
+ if (base.startsWith(".env")) return "environment files are rejected";
598
+ if (base.endsWith(".sh")) return "shell scripts are rejected";
599
+ if (base.endsWith(".node")) return "native addons are rejected";
600
+ if (base.endsWith(".wasm") && !path.startsWith("assets/"))
601
+ return "wasm outside assets/ is rejected";
602
+ return null;
603
+ }
604
+ function isAllowed(path) {
605
+ if (ALLOW_FILES.has(path)) return true;
606
+ if (ALLOW_PREFIXES.some((p) => path.startsWith(p))) return true;
607
+ return ALLOW_PATTERNS.some((re) => re.test(path));
608
+ }
609
+ var IMPORT_SPECIFIER_RE = /(?:\bimport\s*(?:[\w*{}\s,$]*\bfrom\s*)?|\bexport\s+[\w*{}\s,$]*\bfrom\s*|\brequire\s*\(\s*|\bimport\s*\(\s*)['"]([^'"]+)['"]/g;
610
+ function isPlainRegistryRange(spec) {
611
+ if (typeof spec !== "string" || spec.length === 0 || spec.length > 128) return false;
612
+ const comparator = /^(?:[<>]=?|=|~|\^)?v?(?:0|[1-9]\d*|[xX*])(?:\.(?:0|[1-9]\d*|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
613
+ return spec.split("||").every((set) => {
614
+ const parts = set.trim().split(/\s+/);
615
+ if (parts.length === 1 && parts[0] === "") return false;
616
+ if (parts.length === 3 && parts[1] === "-")
617
+ return comparator.test(parts[0]) && comparator.test(parts[2]);
618
+ return parts.every((p) => comparator.test(p));
619
+ });
620
+ }
621
+ function registryVersionOf(version) {
622
+ const m = /^(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(\(.+\))*$/.exec(version);
623
+ return m ? m[1] : void 0;
624
+ }
625
+ function snapshotBase(key) {
626
+ const paren = key.indexOf("(");
627
+ const head = paren >= 0 ? key.slice(0, paren) : key;
628
+ const at = head.lastIndexOf("@");
629
+ if (at <= 0) return void 0;
630
+ const version = registryVersionOf(key.slice(at + 1));
631
+ return version ? `${head.slice(0, at)}@${version}` : void 0;
632
+ }
633
+ function disallowedViteImport(source) {
634
+ for (const match of source.matchAll(IMPORT_SPECIFIER_RE)) {
635
+ const spec = match[1];
636
+ if (spec.startsWith("./") || spec.startsWith("../")) continue;
637
+ if (!VITE_IMPORT_ALLOW.some((re) => re.test(spec))) return spec;
638
+ }
639
+ return null;
640
+ }
641
+ var IngestGate = class {
642
+ constructor(opts) {
643
+ this.opts = opts;
644
+ }
645
+ inspect(input) {
646
+ if (this.opts.thirdParty && !input.some((f) => f.path === "manifest.json"))
647
+ return this.inspectStarter(input);
648
+ const files = sortLeaves(input);
649
+ if (files.length > INGEST_LIMITS.maxEntries) {
650
+ throw new IngestRejectedError(
651
+ "size",
652
+ `${files.length} entries exceeds the ${INGEST_LIMITS.maxEntries} entry cap`
653
+ );
654
+ }
655
+ let total = 0;
656
+ for (const f of files) {
657
+ total += f.bytes.byteLength;
658
+ if (f.bytes.byteLength > INGEST_LIMITS.maxFileBytes) {
659
+ throw new IngestRejectedError(
660
+ "size",
661
+ `${f.path} is ${f.bytes.byteLength} bytes; single file cap is ${INGEST_LIMITS.maxFileBytes}`,
662
+ f.path
663
+ );
664
+ }
665
+ }
666
+ if (total > INGEST_LIMITS.maxUnpackedBytes) {
667
+ throw new IngestRejectedError(
668
+ "size",
669
+ `tree is ${total} bytes; cap is ${INGEST_LIMITS.maxUnpackedBytes}`
670
+ );
671
+ }
672
+ const seen = /* @__PURE__ */ new Set();
673
+ for (const f of files) {
674
+ const problem = relativePathProblem(f.path, { allowDotfiles: true });
675
+ if (problem)
676
+ throw new IngestRejectedError(
677
+ "params",
678
+ `path ${JSON.stringify(f.path)} rejected: ${problem}`,
679
+ f.path
680
+ );
681
+ if (seen.has(f.path))
682
+ throw new IngestRejectedError("params", `duplicate path ${f.path}`, f.path);
683
+ seen.add(f.path);
684
+ const deny = denyReason(f.path);
685
+ if (deny) throw new IngestRejectedError("params", `${f.path}: ${deny}`, f.path);
686
+ const base = basename(f.path);
687
+ if (/^vite(st)?\.config\./.test(base)) {
688
+ const bad = disallowedViteImport(f.bytes.toString("utf8"));
689
+ if (bad) {
690
+ throw new IngestRejectedError(
691
+ "params",
692
+ `${f.path} imports ${JSON.stringify(bad)}, which is not an allowlisted plugin`,
693
+ f.path
694
+ );
695
+ }
696
+ }
697
+ if (!isAllowed(f.path)) {
698
+ throw new IngestRejectedError(
699
+ "params",
700
+ `${f.path} is outside the accepted source layout`,
701
+ f.path
702
+ );
703
+ }
704
+ if (INLINE_SCRIPT_SOURCE.test(f.path)) {
705
+ const inlineProblem = inlineScriptProblem(f.bytes);
706
+ if (inlineProblem)
707
+ throw new IngestRejectedError(
708
+ "params",
709
+ `inline script ${f.path} ${inlineProblem}`,
710
+ f.path
711
+ );
712
+ }
713
+ }
714
+ this.checkCollisions(files);
715
+ const pkgFile = files.find((f) => f.path === "package.json");
716
+ if (!pkgFile)
717
+ throw new IngestRejectedError("params", "package.json is required", "package.json");
718
+ const packageJson = this.checkPackageJson(pkgFile);
719
+ const lockFile = files.find((f) => f.path === "pnpm-lock.yaml");
720
+ if (!lockFile)
721
+ throw new IngestRejectedError("deps", "pnpm-lock.yaml is required", "pnpm-lock.yaml");
722
+ const lockfile = this.checkLockfile(lockFile);
723
+ const manifestFile = files.find((f) => f.path === "manifest.json");
724
+ if (!manifestFile)
725
+ throw new IngestRejectedError("manifest", "manifest.json is required", "manifest.json");
726
+ const manifest = this.checkManifest(manifestFile);
727
+ return {
728
+ files,
729
+ sourceDigest: sourceDigestOf(leavesOf(files)),
730
+ lockfileDigest: sha256Digest(lockFile.bytes),
731
+ lockfile,
732
+ manifest,
733
+ abiVersion: manifest.abi,
734
+ layout: "theme-source",
735
+ packageJson
736
+ };
737
+ }
738
+ /**
739
+ * A starter tree (third-party lane, D18 option a). What is accepted:
740
+ * - paths that are not build inputs (tests, CI, agent/editor config, build output) are DROPPED before
741
+ * the source digest; the platform's deny-list (npm/pnpm/yarn config, Dockerfiles, env files, shell
742
+ * scripts, native addons, wasm outside assets/) still REJECTS; every other path is a build input —
743
+ * the theme's own build file runs over the whole tree in the sandbox;
744
+ * - package.json: name + version; `tanqory.build` (a relative .mjs that exists; default: the
745
+ * starters' own) and `tanqory.out` (default dist/abi); dependencies only platform packages at exact
746
+ * versions, packages the image provides (react, react-dom, vite, @vitejs/plugin-react; the image's
747
+ * versions are used, never the declared range) and — devDependencies only — developer tools the build
748
+ * never runs; resolutions/workspaces/overrides/patches rejected as for any theme;
749
+ * - a lockfile is optional (npm or pnpm): never installed from, read for the SBOM only;
750
+ * - no manifest.json: the build writes it, and the platform checks the build's output.
751
+ */
752
+ inspectStarter(input) {
753
+ const files = sortLeaves(input.filter((f) => !isStarterIgnoredPath(f.path)));
754
+ if (files.length > INGEST_LIMITS.maxEntries)
755
+ throw new IngestRejectedError(
756
+ "size",
757
+ `${files.length} entries exceeds the ${INGEST_LIMITS.maxEntries} entry cap`
758
+ );
759
+ let total = 0;
760
+ const seen = /* @__PURE__ */ new Set();
761
+ for (const f of files) {
762
+ total += f.bytes.byteLength;
763
+ if (f.bytes.byteLength > INGEST_LIMITS.maxFileBytes)
764
+ throw new IngestRejectedError(
765
+ "size",
766
+ `${f.path} is ${f.bytes.byteLength} bytes; single file cap is ${INGEST_LIMITS.maxFileBytes}`,
767
+ f.path
768
+ );
769
+ const problem = relativePathProblem(f.path, { allowDotfiles: true });
770
+ if (problem)
771
+ throw new IngestRejectedError(
772
+ "params",
773
+ `path ${JSON.stringify(f.path)} rejected: ${problem}`,
774
+ f.path
775
+ );
776
+ if (seen.has(f.path))
777
+ throw new IngestRejectedError("params", `duplicate path ${f.path}`, f.path);
778
+ seen.add(f.path);
779
+ const deny = denyReason(f.path);
780
+ if (deny) throw new IngestRejectedError("params", `${f.path}: ${deny}`, f.path);
781
+ }
782
+ if (total > INGEST_LIMITS.maxUnpackedBytes)
783
+ throw new IngestRejectedError(
784
+ "size",
785
+ `tree is ${total} bytes; cap is ${INGEST_LIMITS.maxUnpackedBytes}`
786
+ );
787
+ const folded = /* @__PURE__ */ new Map();
788
+ for (const f of files) {
789
+ const key = f.path.normalize("NFC").toLowerCase();
790
+ const other = folded.get(key);
791
+ if (other)
792
+ throw new PathCollisionError(`${f.path} collides with ${other} when case is ignored`, [
793
+ other,
794
+ f.path
795
+ ]);
796
+ folded.set(key, f.path);
797
+ }
798
+ const pkgFile = files.find((f) => f.path === "package.json");
799
+ if (!pkgFile)
800
+ throw new IngestRejectedError("params", "package.json is required", "package.json");
801
+ const packageJson = this.checkStarterPackageJson(pkgFile, new Set(files.map((f) => f.path)));
802
+ const pnpmLock = files.find((f) => f.path === "pnpm-lock.yaml");
803
+ const npmLock = files.find((f) => f.path === "package-lock.json");
804
+ let lockfile;
805
+ try {
806
+ lockfile = pnpmLock ? parsePnpmLockfile(pnpmLock.bytes) : npmLock ? parseNpmLockfile(npmLock.bytes) : EMPTY_LOCKFILE;
807
+ } catch (e) {
808
+ throw new IngestRejectedError(
809
+ "deps",
810
+ `${(pnpmLock ?? npmLock).path}: ${e.message}`,
811
+ (pnpmLock ?? npmLock).path
812
+ );
813
+ }
814
+ return {
815
+ files,
816
+ sourceDigest: sourceDigestOf(leavesOf(files)),
817
+ lockfileDigest: sha256Digest((pnpmLock ?? npmLock)?.bytes ?? Buffer.alloc(0)),
818
+ lockfile,
819
+ abiVersion: STARTER_ABI_VERSION,
820
+ layout: "starter",
821
+ packageJson
822
+ };
823
+ }
824
+ checkStarterPackageJson(file, paths) {
825
+ let pkg;
826
+ try {
827
+ pkg = JSON.parse(file.bytes.toString("utf8"));
828
+ } catch {
829
+ throw new IngestRejectedError("params", "package.json is not valid JSON", file.path);
830
+ }
831
+ if (typeof pkg["name"] !== "string" || typeof pkg["version"] !== "string")
832
+ throw new IngestRejectedError(
833
+ "params",
834
+ 'package.json needs string "name" and "version"',
835
+ file.path
836
+ );
837
+ for (const key of ["resolutions", "workspaces", "overrides"])
838
+ if (key in pkg)
839
+ throw new IngestRejectedError("params", `package.json "${key}" is rejected`, file.path);
840
+ const pnpm = pkg["pnpm"] ?? {};
841
+ for (const key of ["overrides", "patchedDependencies", "onlyBuiltDependencies"])
842
+ if (key in pnpm)
843
+ throw new IngestRejectedError("params", `package.json "pnpm.${key}" is rejected`, file.path);
844
+ const tq = pkg["tanqory"] ?? {};
845
+ if (typeof tq !== "object" || Array.isArray(tq))
846
+ throw new IngestRejectedError("params", 'package.json "tanqory" must be an object', file.path);
847
+ const build = tq["build"] ?? STARTER_DEFAULT_BUILDS.find((b) => paths.has(b)) ?? STARTER_DEFAULT_BUILDS[1];
848
+ const out = tq["out"] ?? STARTER_DEFAULT_OUT;
849
+ if (typeof build !== "string" || !STARTER_PATH_RE.test(build) || !build.endsWith(".mjs"))
850
+ throw new IngestRejectedError(
851
+ "params",
852
+ `package.json tanqory.build ${JSON.stringify(build)} must be a relative path to a .mjs file in the theme`,
853
+ file.path
854
+ );
855
+ if (!paths.has(build))
856
+ throw new IngestRejectedError(
857
+ "params",
858
+ `the build file ${build} is not in the upload (package.json tanqory.build, or ${STARTER_DEFAULT_BUILDS.join(" / ")})`,
859
+ build
860
+ );
861
+ if (typeof out !== "string" || !STARTER_PATH_RE.test(out))
862
+ throw new IngestRejectedError(
863
+ "params",
864
+ `package.json tanqory.out ${JSON.stringify(out)} must be a relative directory in the theme`,
865
+ file.path
866
+ );
867
+ const sections = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
868
+ let kit = false;
869
+ for (const section of sections) {
870
+ const deps = pkg[section] ?? {};
871
+ for (const [name, spec] of Object.entries(deps)) {
872
+ if (typeof spec !== "string" || !isPlainRegistryRange(spec))
873
+ throw new IngestRejectedError(
874
+ "deps",
875
+ `package.json ${section}.${name}: ${JSON.stringify(spec)} is not a plain registry version range`,
876
+ file.path,
877
+ { entry: name }
878
+ );
879
+ const platform = THIRD_PARTY_PLATFORM_PACKAGES.get(name);
880
+ if (platform) {
881
+ const allowed = PLATFORM_PACKAGE_SECTIONS[platform];
882
+ if (!allowed.includes(section))
883
+ throw new IngestRejectedError(
884
+ "deps",
885
+ `package.json ${section}.${name}: ${name} may be named only in ${allowed.join(" or ")}`,
886
+ file.path,
887
+ { entry: name }
888
+ );
889
+ if (!EXACT_VERSION_RE.test(spec))
890
+ throw new IngestRejectedError(
891
+ "deps",
892
+ `package.json ${section}.${name}: ${JSON.stringify(spec)} must be an exact version (e.g. "2.0.0-alpha.3"), not a range`,
893
+ file.path,
894
+ { entry: name }
895
+ );
896
+ if (name === "@tanqory/theme-kit") kit = true;
897
+ continue;
898
+ }
899
+ if (STARTER_PROVIDED_PACKAGES.has(name) && (section === "dependencies" || section === "devDependencies"))
900
+ continue;
901
+ if (isStarterDevTool(name) && section === "devDependencies") continue;
902
+ throw new IngestRejectedError(
903
+ "deps",
904
+ `package.json ${section}.${name}: the builder does not provide ${name} (a starter build uses the kit, react, react-dom, vite and @vitejs/plugin-react from the builder image)`,
905
+ file.path,
906
+ { entry: name }
907
+ );
908
+ }
909
+ }
910
+ if (!kit)
911
+ throw new IngestRejectedError(
912
+ "deps",
913
+ "package.json must pin @tanqory/theme-kit exactly: it selects the toolchain the build runs with",
914
+ file.path,
915
+ { entry: "@tanqory/theme-kit" }
916
+ );
917
+ return { name: pkg["name"], version: pkg["version"] };
918
+ }
919
+ checkCollisions(files) {
920
+ const folded = /* @__PURE__ */ new Map();
921
+ for (const f of files) {
922
+ const key = f.path.normalize("NFC").toLowerCase();
923
+ const other = folded.get(key);
924
+ if (other) {
925
+ throw new PathCollisionError(`${f.path} collides with ${other} when case is ignored`, [
926
+ other,
927
+ f.path
928
+ ]);
929
+ }
930
+ folded.set(key, f.path);
931
+ }
932
+ for (const prefix of FLATTENED_PREFIXES) {
933
+ const byBase = /* @__PURE__ */ new Map();
934
+ for (const f of files) {
935
+ if (!f.path.startsWith(prefix)) continue;
936
+ const base = basename(f.path);
937
+ const other = byBase.get(base);
938
+ if (other) {
939
+ throw new PathCollisionError(
940
+ `${other} and ${f.path} both map to ${prefix}${base} in the artifact`,
941
+ [other, f.path]
942
+ );
943
+ }
944
+ byBase.set(base, f.path);
945
+ }
946
+ }
947
+ }
948
+ checkPackageJson(file) {
949
+ let pkg;
950
+ try {
951
+ pkg = JSON.parse(file.bytes.toString("utf8"));
952
+ } catch {
953
+ throw new IngestRejectedError("params", "package.json is not valid JSON", file.path);
954
+ }
955
+ if (typeof pkg["name"] !== "string" || typeof pkg["version"] !== "string") {
956
+ throw new IngestRejectedError(
957
+ "params",
958
+ 'package.json needs string "name" and "version"',
959
+ file.path
960
+ );
961
+ }
962
+ for (const key of ["resolutions", "workspaces"]) {
963
+ if (key in pkg)
964
+ throw new IngestRejectedError("params", `package.json "${key}" is rejected`, file.path);
965
+ }
966
+ const pnpm = pkg["pnpm"] ?? {};
967
+ for (const key of ["overrides", "patchedDependencies"]) {
968
+ if (key in pnpm)
969
+ throw new IngestRejectedError("params", `package.json "pnpm.${key}" is rejected`, file.path);
970
+ }
971
+ const onlyBuilt = pnpm["onlyBuiltDependencies"];
972
+ if (onlyBuilt !== void 0 && !(Array.isArray(onlyBuilt) && onlyBuilt.length === 0)) {
973
+ throw new IngestRejectedError(
974
+ "deps",
975
+ 'package.json "pnpm.onlyBuiltDependencies" must be absent or []',
976
+ file.path
977
+ );
978
+ }
979
+ for (const section of [
980
+ "dependencies",
981
+ "devDependencies",
982
+ "optionalDependencies",
983
+ "peerDependencies"
984
+ ]) {
985
+ const deps = pkg[section] ?? {};
986
+ for (const [name, spec] of Object.entries(deps)) {
987
+ if (typeof spec !== "string" || !isPlainRegistryRange(spec)) {
988
+ throw new IngestRejectedError(
989
+ "deps",
990
+ `package.json ${section}.${name}: ${JSON.stringify(spec)} is not a plain registry version range`,
991
+ file.path,
992
+ { entry: name }
993
+ );
994
+ }
995
+ const platform = this.opts.thirdParty ? THIRD_PARTY_PLATFORM_PACKAGES.get(name) : void 0;
996
+ if (platform) {
997
+ const sections = PLATFORM_PACKAGE_SECTIONS[platform];
998
+ if (!sections.includes(section))
999
+ throw new IngestRejectedError(
1000
+ "deps",
1001
+ `package.json ${section}.${name}: ${name} may be named only in ${sections.join(" or ")}`,
1002
+ file.path,
1003
+ { entry: name }
1004
+ );
1005
+ if (!EXACT_VERSION_RE.test(spec))
1006
+ throw new IngestRejectedError(
1007
+ "deps",
1008
+ `package.json ${section}.${name}: ${JSON.stringify(spec)} must be an exact version (e.g. "2.0.0-alpha.3"), not a range`,
1009
+ file.path,
1010
+ { entry: name }
1011
+ );
1012
+ continue;
1013
+ }
1014
+ if (isToolchainPackage(name)) {
1015
+ throw new IngestRejectedError(
1016
+ "deps",
1017
+ `package.json ${section}.${name}: toolchain packages are provided by the builder image`,
1018
+ file.path,
1019
+ { entry: name }
1020
+ );
1021
+ }
1022
+ }
1023
+ }
1024
+ for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
1025
+ const deps = pkg[section] ?? {};
1026
+ for (const name of Object.keys(deps)) {
1027
+ if (this.opts.thirdParty && THIRD_PARTY_PLATFORM_PACKAGES.has(name)) continue;
1028
+ if (!this.opts.allowlist.packages.has(name)) {
1029
+ throw new IngestRejectedError(
1030
+ "deps",
1031
+ `package.json ${section}.${name} is not on the mirror allowlist`,
1032
+ file.path,
1033
+ { entry: name }
1034
+ );
1035
+ }
1036
+ }
1037
+ }
1038
+ return { name: pkg["name"], version: pkg["version"] };
1039
+ }
1040
+ checkLockfile(file) {
1041
+ let lock;
1042
+ try {
1043
+ lock = parsePnpmLockfile(file.bytes);
1044
+ } catch (e) {
1045
+ throw new IngestRejectedError("deps", e.message, file.path);
1046
+ }
1047
+ const major = Number.parseInt(lock.lockfileVersion, 10);
1048
+ if (!Number.isFinite(major) || major < 9) {
1049
+ throw new IngestRejectedError(
1050
+ "deps",
1051
+ `pnpm-lock.yaml lockfileVersion ${lock.lockfileVersion} < 9`,
1052
+ file.path
1053
+ );
1054
+ }
1055
+ const platformOnly = this.opts.thirdParty ? platformOnlyClosure(lock) : /* @__PURE__ */ new Set();
1056
+ for (const p of lock.packages) {
1057
+ const entry = `${p.name}@${p.version}`;
1058
+ if (platformOnly.has(entry)) {
1059
+ if (!p.integrity || !/^sha512-/.test(p.integrity))
1060
+ throw new IngestRejectedError(
1061
+ "deps",
1062
+ `pnpm-lock.yaml ${entry} has no sha512 resolution.integrity`,
1063
+ file.path,
1064
+ { entry }
1065
+ );
1066
+ } else if (isToolchainPackage(p.name)) {
1067
+ throw new IngestRejectedError(
1068
+ "deps",
1069
+ `pnpm-lock.yaml ${entry}: toolchain packages are provided by the builder image`,
1070
+ file.path,
1071
+ { entry }
1072
+ );
1073
+ }
1074
+ const problem = platformOnly.has(entry) ? void 0 : allowlistProblem(this.opts.allowlist, p.name, p.version, p.integrity);
1075
+ if (problem) {
1076
+ throw new IngestRejectedError("deps", `pnpm-lock.yaml ${entry} ${problem}`, file.path, {
1077
+ entry
1078
+ });
1079
+ }
1080
+ if (p.tarball) {
1081
+ let host;
1082
+ try {
1083
+ host = new URL(p.tarball).host;
1084
+ } catch {
1085
+ throw new IngestRejectedError(
1086
+ "deps",
1087
+ `pnpm-lock.yaml ${entry}: resolution.tarball is not a URL`,
1088
+ file.path,
1089
+ { entry }
1090
+ );
1091
+ }
1092
+ if (!this.opts.mirrorHosts.includes(host)) {
1093
+ throw new IngestRejectedError(
1094
+ "deps",
1095
+ `pnpm-lock.yaml ${entry}: tarball host ${host} is not the mirror`,
1096
+ file.path,
1097
+ { entry }
1098
+ );
1099
+ }
1100
+ }
1101
+ }
1102
+ const checked = new Set(lock.packages.map((p) => `${p.name}@${p.version}`));
1103
+ const refuse = (message, entry) => {
1104
+ throw new IngestRejectedError("deps", `pnpm-lock.yaml ${message}`, file.path, { entry });
1105
+ };
1106
+ for (const d of lock.importerDependencies) {
1107
+ const at = `importers[${JSON.stringify(d.importer)}].${d.section}.${d.name}`;
1108
+ if (d.importer !== ".") refuse(`${at}: only the root importer "." is accepted`, d.name);
1109
+ if (d.section === "peerDependencies")
1110
+ refuse(`${at}: an importer peer dependency is not accepted`, d.name);
1111
+ if (!isPlainRegistryRange(d.specifier))
1112
+ refuse(
1113
+ `${at}: specifier ${JSON.stringify(d.specifier)} is not a plain registry range`,
1114
+ d.name
1115
+ );
1116
+ const version = registryVersionOf(d.version);
1117
+ if (!version)
1118
+ refuse(`${at}: version ${JSON.stringify(d.version)} is not a registry version`, d.name);
1119
+ if (!checked.has(`${d.name}@${version}`))
1120
+ refuse(`${at}: ${d.name}@${version} has no entry in packages:`, d.name);
1121
+ if (this.opts.thirdParty && THIRD_PARTY_PLATFORM_PACKAGES.has(d.name) && d.specifier !== version)
1122
+ refuse(
1123
+ `${at}: specifier ${d.specifier} must be the exact version it resolves to (${version})`,
1124
+ d.name
1125
+ );
1126
+ }
1127
+ for (const snap of lock.snapshots) {
1128
+ const base = snapshotBase(snap.key);
1129
+ if (!base || !checked.has(base))
1130
+ refuse(
1131
+ `snapshots[${JSON.stringify(snap.key)}] names a package that packages: does not list`,
1132
+ snap.key
1133
+ );
1134
+ for (const d of snap.dependencies) {
1135
+ const version = registryVersionOf(d.version);
1136
+ if (!version || !checked.has(`${d.name}@${version}`))
1137
+ refuse(
1138
+ `snapshots[${JSON.stringify(snap.key)}].${d.name}: ${JSON.stringify(d.version)} does not resolve to an entry of packages:`,
1139
+ snap.key
1140
+ );
1141
+ }
1142
+ }
1143
+ return lock;
1144
+ }
1145
+ checkManifest(file) {
1146
+ if (file.bytes.byteLength > import_theme_abi.LIMITS.manifestBytes.hard) {
1147
+ throw new IngestRejectedError(
1148
+ "manifest",
1149
+ `manifest.json is ${file.bytes.byteLength} bytes; hard limit ${import_theme_abi.LIMITS.manifestBytes.hard}`,
1150
+ file.path
1151
+ );
1152
+ }
1153
+ let parsed;
1154
+ try {
1155
+ parsed = JSON.parse(file.bytes.toString("utf8"));
1156
+ } catch {
1157
+ throw new IngestRejectedError("manifest", "manifest.json is not valid JSON", file.path);
1158
+ }
1159
+ const result = (0, import_theme_abi.validateManifest)(parsed);
1160
+ if (!result.ok) {
1161
+ const first = result.errors[0];
1162
+ throw new IngestRejectedError(
1163
+ "manifest",
1164
+ `manifest.json invalid: ${first ? `${first.path || "/"}: ${first.message}` : "unknown error"}`,
1165
+ file.path,
1166
+ {
1167
+ errors: result.errors.map((e) => ({
1168
+ path: e.path,
1169
+ code: e.code,
1170
+ keyword: e.keyword,
1171
+ message: e.message
1172
+ }))
1173
+ }
1174
+ );
1175
+ }
1176
+ return result.manifest;
1177
+ }
1178
+ };
1179
+ function platformOnlyClosure(lock) {
1180
+ const edges = /* @__PURE__ */ new Map();
1181
+ for (const snap of lock.snapshots) {
1182
+ const base = snapshotBase(snap.key);
1183
+ if (!base) continue;
1184
+ const out = edges.get(base) ?? [];
1185
+ for (const d of snap.dependencies) {
1186
+ const v = registryVersionOf(d.version);
1187
+ if (v) out.push(`${d.name}@${v}`);
1188
+ }
1189
+ edges.set(base, out);
1190
+ }
1191
+ const reach = (roots) => {
1192
+ const seen = /* @__PURE__ */ new Set();
1193
+ const stack = [...roots];
1194
+ while (stack.length > 0) {
1195
+ const k = stack.pop();
1196
+ if (seen.has(k)) continue;
1197
+ seen.add(k);
1198
+ stack.push(...edges.get(k) ?? []);
1199
+ }
1200
+ return seen;
1201
+ };
1202
+ const platformRoots = [];
1203
+ const otherRoots = [];
1204
+ for (const d of lock.importerDependencies) {
1205
+ if (d.importer !== ".") continue;
1206
+ const v = registryVersionOf(d.version);
1207
+ if (!v) continue;
1208
+ (THIRD_PARTY_PLATFORM_PACKAGES.has(d.name) ? platformRoots : otherRoots).push(`${d.name}@${v}`);
1209
+ }
1210
+ const other = reach(otherRoots);
1211
+ return new Set([...reach(platformRoots)].filter((k) => !other.has(k)));
1212
+ }
1213
+ var EMPTY_LOCKFILE = Object.freeze({
1214
+ lockfileVersion: "none",
1215
+ packages: [],
1216
+ rootDependencies: {},
1217
+ importerDependencies: [],
1218
+ snapshots: []
1219
+ });
1220
+ function parseNpmLockfile(bytes) {
1221
+ let doc;
1222
+ try {
1223
+ doc = JSON.parse(Buffer.from(bytes).toString("utf8"));
1224
+ } catch {
1225
+ throw new Error("not valid JSON");
1226
+ }
1227
+ if (typeof doc.lockfileVersion !== "number" || doc.lockfileVersion < 2 || !doc.packages)
1228
+ throw new Error('package-lock.json lockfileVersion must be 2 or 3 with a "packages" map');
1229
+ const packages = [];
1230
+ const seen = /* @__PURE__ */ new Set();
1231
+ for (const [key, entry] of Object.entries(doc.packages)) {
1232
+ if (!key.startsWith("node_modules/") || entry["link"]) continue;
1233
+ const name = key.slice(key.lastIndexOf("node_modules/") + "node_modules/".length);
1234
+ const version = entry["version"];
1235
+ if (typeof version !== "string" || seen.has(`${name}@${version}`)) continue;
1236
+ seen.add(`${name}@${version}`);
1237
+ packages.push({
1238
+ name,
1239
+ version,
1240
+ ...typeof entry["integrity"] === "string" ? { integrity: entry["integrity"] } : {}
1241
+ });
1242
+ }
1243
+ const root = doc.packages[""] ?? {};
1244
+ const rootDependencies = {};
1245
+ for (const section of ["dependencies", "devDependencies"])
1246
+ for (const name of Object.keys(root[section] ?? {})) {
1247
+ const v = doc.packages[`node_modules/${name}`]?.["version"];
1248
+ if (typeof v === "string") rootDependencies[name] = v;
1249
+ }
1250
+ return {
1251
+ lockfileVersion: String(doc.lockfileVersion),
1252
+ packages,
1253
+ rootDependencies,
1254
+ importerDependencies: [],
1255
+ snapshots: []
1256
+ };
1257
+ }
1258
+
1259
+ // ../../apps/build-service/src/ingest/archive-guard.ts
1260
+ async function extractTarballGuarded(input, limits = INGEST_LIMITS) {
1261
+ const files = [];
1262
+ let archiveBytes = 0;
1263
+ let unpackedBytes = 0;
1264
+ let entries = 0;
1265
+ let failure2;
1266
+ const hash = (0, import_node_crypto3.createHash)("sha256");
1267
+ const parser = new tar.Parser({ strict: true });
1268
+ const fail = (err) => {
1269
+ if (!failure2) failure2 = err;
1270
+ parser.abort(err);
1271
+ };
1272
+ const normalisePath = (raw) => {
1273
+ let p = raw;
1274
+ while (p.startsWith("./")) p = p.slice(2);
1275
+ if (p.endsWith("/")) p = p.slice(0, -1);
1276
+ return p;
1277
+ };
1278
+ parser.on("entry", (entry) => {
1279
+ entries += 1;
1280
+ if (entries > limits.maxEntries) {
1281
+ fail(new UnsafeArchiveError(`archive has more than ${limits.maxEntries} entries`));
1282
+ entry.resume();
1283
+ return;
1284
+ }
1285
+ const path = normalisePath(entry.path);
1286
+ if (entry.type === "Directory") {
1287
+ if (path !== "" && relativePathProblem(path, { allowDotfiles: true })) {
1288
+ fail(
1289
+ new UnsafeArchiveError(`unsafe directory name ${JSON.stringify(entry.path)}`, entry.path)
1290
+ );
1291
+ }
1292
+ entry.resume();
1293
+ return;
1294
+ }
1295
+ if (entry.type !== "File") {
1296
+ fail(
1297
+ new UnsafeArchiveError(
1298
+ `entry ${JSON.stringify(entry.path)} is a ${entry.type}; only files and directories are accepted`,
1299
+ entry.path
1300
+ )
1301
+ );
1302
+ entry.resume();
1303
+ return;
1304
+ }
1305
+ const problem = relativePathProblem(path, { allowDotfiles: true });
1306
+ if (problem) {
1307
+ fail(
1308
+ new UnsafeArchiveError(
1309
+ `unsafe entry name ${JSON.stringify(entry.path)}: ${problem}`,
1310
+ entry.path
1311
+ )
1312
+ );
1313
+ entry.resume();
1314
+ return;
1315
+ }
1316
+ if (entry.size > limits.maxFileBytes) {
1317
+ fail(
1318
+ new UnsafeArchiveError(
1319
+ `${path} is ${entry.size} bytes; single file cap is ${limits.maxFileBytes}`,
1320
+ path
1321
+ )
1322
+ );
1323
+ entry.resume();
1324
+ return;
1325
+ }
1326
+ unpackedBytes += entry.size;
1327
+ if (unpackedBytes > limits.maxUnpackedBytes) {
1328
+ fail(new UnsafeArchiveError(`unpacked size exceeds ${limits.maxUnpackedBytes} bytes`, path));
1329
+ entry.resume();
1330
+ return;
1331
+ }
1332
+ const chunks = [];
1333
+ entry.on("data", (c) => chunks.push(c));
1334
+ entry.on("end", () => {
1335
+ if (!failure2) files.push({ path, bytes: Buffer.concat(chunks) });
1336
+ });
1337
+ });
1338
+ const done = new Promise((resolve, reject) => {
1339
+ parser.on("end", resolve);
1340
+ parser.on("error", reject);
1341
+ parser.on("abort", () => reject(failure2 ?? new UnsafeArchiveError("archive parsing aborted")));
1342
+ });
1343
+ try {
1344
+ for await (const chunk of input) {
1345
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1346
+ archiveBytes += buf.byteLength;
1347
+ if (archiveBytes > limits.maxArchiveBytes) {
1348
+ fail(new UnsafeArchiveError(`archive exceeds ${limits.maxArchiveBytes} bytes`));
1349
+ break;
1350
+ }
1351
+ hash.update(buf);
1352
+ parser.write(buf);
1353
+ if (archiveBytes >= limits.ratioCheckAfterBytes && unpackedBytes / archiveBytes > limits.maxCompressionRatio) {
1354
+ fail(new UnsafeArchiveError(`compression ratio exceeds ${limits.maxCompressionRatio}`));
1355
+ break;
1356
+ }
1357
+ if (failure2) break;
1358
+ }
1359
+ if (!failure2) parser.end();
1360
+ await done;
1361
+ } catch (e) {
1362
+ if (failure2) throw failure2;
1363
+ if (e instanceof UnsafeArchiveError) throw e;
1364
+ throw new UnsafeArchiveError(`archive is not a readable tar(.gz): ${e.message}`);
1365
+ }
1366
+ if (failure2) throw failure2;
1367
+ return {
1368
+ files: sortLeaves(files),
1369
+ archiveBytes,
1370
+ unpackedBytes,
1371
+ archiveSha256: hash.digest("hex")
1372
+ };
1373
+ }
1374
+
1375
+ // ../../apps/build-service/src/review/static-checks.ts
1376
+ var import_node_fs3 = require("node:fs");
1377
+ var import_node_path3 = require("node:path");
1378
+ var import_acorn = require("acorn");
1379
+ var import_acorn_walk = require("acorn-walk");
1380
+ var import_zod = require("zod");
1381
+ var FINDINGS_MAX = 50;
1382
+ var isClientScript = (p) => /^client\/assets\/[A-Za-z0-9._-]+\.m?js$/.test(p);
1383
+ var calleeName = (callee) => {
1384
+ if (callee.type === "Identifier") return callee.name;
1385
+ if (callee.type === "MemberExpression" && !callee.computed && callee.property?.type === "Identifier") return callee.property.name;
1386
+ if (callee.type === "MemberExpression" && callee.computed && callee.property?.type === "Literal" && typeof callee.property.value === "string") return callee.property.value;
1387
+ if (callee.type === "SequenceExpression") return calleeName(callee.expressions[callee.expressions.length - 1]);
1388
+ return null;
1389
+ };
1390
+ function evalFindings(path, source) {
1391
+ let ast;
1392
+ try {
1393
+ ast = (0, import_acorn.parse)(source, { ecmaVersion: "latest", sourceType: "module", locations: true });
1394
+ } catch {
1395
+ try {
1396
+ ast = (0, import_acorn.parse)(source, { ecmaVersion: "latest", sourceType: "script", locations: true });
1397
+ } catch (e) {
1398
+ return [{ path, code: "parse_error", message: `${path} does not parse as JavaScript: ${e.message}` }];
1399
+ }
1400
+ }
1401
+ const out = [];
1402
+ const at = (n) => `${path}:${n.loc?.start.line ?? 0}:${(n.loc?.start.column ?? 0) + 1}`;
1403
+ (0, import_acorn_walk.full)(ast, (node) => {
1404
+ if (node.type !== "CallExpression" && node.type !== "NewExpression") return;
1405
+ const n = node;
1406
+ const name = calleeName(n.callee);
1407
+ if (name === "eval" && node.type === "CallExpression") out.push({ path: at(node), code: "eval", message: `${at(node)} calls eval(). Remove it: the storefront never allows code from strings.` });
1408
+ else if (name === "Function") out.push({ path: at(node), code: "new_function", message: `${at(node)} builds a function from a string (${node.type === "NewExpression" ? "new " : ""}Function). Remove it: the storefront never allows code from strings.` });
1409
+ else if ((name === "setTimeout" || name === "setInterval") && node.type === "CallExpression") {
1410
+ const first = n.arguments?.[0];
1411
+ if (first && (first.type === "Literal" && typeof first.value === "string" || first.type === "TemplateLiteral"))
1412
+ out.push({ path: at(node), code: "string_timer", message: `${at(node)} passes a string to ${name}. Pass a function instead.` });
1413
+ }
1414
+ });
1415
+ return out;
1416
+ }
1417
+ function noEvalLine(files) {
1418
+ const scripts = files.filter((f) => isClientScript(f.path));
1419
+ const errors = scripts.flatMap((f) => evalFindings(f.path, f.bytes.toString("utf8"))).slice(0, FINDINGS_MAX);
1420
+ return errors.length ? { status: "failed", message: errors[0].message, errors } : { status: "passed", message: `No eval, new Function or string timer in ${scripts.length} client script(s).`, errors: [] };
1421
+ }
1422
+ var themeLicencesSchema = import_zod.z.object({
1423
+ $comment: import_zod.z.string().optional(),
1424
+ allowlist: import_zod.z.array(import_zod.z.string().regex(/^[A-Za-z0-9.+-]+$/)).min(1),
1425
+ sources: import_zod.z.array(import_zod.z.string().min(1)).min(1),
1426
+ packages: import_zod.z.record(import_zod.z.string())
1427
+ });
1428
+ var DEFAULT_THEME_LICENCES_PATH = (0, import_node_path3.join)(__dirname, "..", "..", "config", "theme-licences.json");
1429
+ function loadThemeLicences(path = DEFAULT_THEME_LICENCES_PATH) {
1430
+ const parsed = themeLicencesSchema.safeParse(JSON.parse((0, import_node_fs3.readFileSync)(path, "utf8")));
1431
+ if (!parsed.success) throw new Error(`theme licence table ${path} is invalid: ${parsed.error.issues[0]?.message}`);
1432
+ return parsed.data;
1433
+ }
1434
+ function expressionAllowed(expr, allow) {
1435
+ const tokens = expr.replace(/[()]/g, (m) => ` ${m} `).trim().split(/\s+/).filter(Boolean);
1436
+ let i = 0;
1437
+ const primary = () => {
1438
+ const t = tokens[i++];
1439
+ if (t === void 0) return null;
1440
+ if (t === "(") {
1441
+ const v2 = orExpr();
1442
+ if (tokens[i++] !== ")") return null;
1443
+ return v2;
1444
+ }
1445
+ if (/^(AND|OR|WITH|\))$/i.test(t)) return null;
1446
+ if (tokens[i]?.toUpperCase() === "WITH") {
1447
+ i += 2;
1448
+ return false;
1449
+ }
1450
+ return !t.endsWith("+") && allow.has(t);
1451
+ };
1452
+ const andExpr = () => {
1453
+ let v2 = primary();
1454
+ while (v2 !== null && tokens[i]?.toUpperCase() === "AND") {
1455
+ i++;
1456
+ const r = primary();
1457
+ v2 = r === null ? null : v2 && r;
1458
+ }
1459
+ return v2;
1460
+ };
1461
+ function orExpr() {
1462
+ let v2 = andExpr();
1463
+ while (v2 !== null && tokens[i]?.toUpperCase() === "OR") {
1464
+ i++;
1465
+ const r = andExpr();
1466
+ v2 = r === null ? null : v2 || r;
1467
+ }
1468
+ return v2;
1469
+ }
1470
+ const v = orExpr();
1471
+ return v === true && i === tokens.length;
1472
+ }
1473
+ function licenceOf(table, name, version) {
1474
+ const exact = table.packages[`${name}@${version}`] ?? table.packages[name];
1475
+ if (exact !== void 0) return exact;
1476
+ for (const [k, v] of Object.entries(table.packages)) {
1477
+ if (!k.includes("*")) continue;
1478
+ const re = new RegExp(`^${k.split("*").map((x) => x.replace(/[.+?^${}()|[\]\\/]/g, "\\$&")).join("[^/@]*")}$`);
1479
+ if (re.test(name)) return v;
1480
+ }
1481
+ return void 0;
1482
+ }
1483
+ function licencesLine(files, table) {
1484
+ const errors = [];
1485
+ if (!files.some((f) => f.path === "LICENSE"))
1486
+ errors.push({ path: "LICENSE", code: "licence_file_missing", message: "The theme has no LICENSE file. Add one at the root of the source: it is copied into the artifact." });
1487
+ const sbomFile = files.find((f) => f.path === "sbom.cdx.json");
1488
+ let components = [];
1489
+ if (!sbomFile) errors.push({ path: "sbom.cdx.json", code: "sbom_missing", message: "The artifact has no sbom.cdx.json." });
1490
+ else {
1491
+ try {
1492
+ const doc = JSON.parse(sbomFile.bytes.toString("utf8"));
1493
+ components = Array.isArray(doc.components) ? doc.components : [];
1494
+ } catch {
1495
+ errors.push({ path: "sbom.cdx.json", code: "sbom_invalid", message: "sbom.cdx.json is not JSON." });
1496
+ }
1497
+ }
1498
+ const allow = new Set(table.allowlist);
1499
+ for (const c of components) {
1500
+ const name = typeof c.name === "string" ? c.name : "?";
1501
+ const version = typeof c.version === "string" ? c.version : "?";
1502
+ const licence = licenceOf(table, name, version);
1503
+ if (licence === void 0)
1504
+ errors.push({ path: `${name}@${version}`, code: "licence_unknown", message: `${name}@${version} is neither a toolchain package nor on the mirror allowlist, so its licence is not known. Use only those packages.` });
1505
+ else if (!expressionAllowed(licence, allow))
1506
+ errors.push({ path: `${name}@${version}`, code: "licence_not_allowed", message: `${name}@${version} is licensed ${licence}, which is not on the allowed list (${table.allowlist.join(", ")}).` });
1507
+ if (errors.length >= FINDINGS_MAX) break;
1508
+ }
1509
+ return errors.length ? { status: "failed", message: errors[0].message, errors: errors.slice(0, FINDINGS_MAX) } : { status: "passed", message: `A LICENSE file, and ${components.length} SBOM component(s) all on the allowed licence list.`, errors: [] };
1510
+ }
1511
+
1512
+ // ../../apps/build-service/src/review/partner-source.ts
1513
+ var BRAND_RE = new RegExp(Buffer.from("c2hvcGlmeQ==", "base64").toString(), "i");
1514
+ var EMOJI = /([\p{Extended_Pictographic}\u{1F1E6}-\u{1F1FF}])(\u{FE0F})?/gu;
1515
+ var TEXT_FORM_ALLOWED = /* @__PURE__ */ new Set(["\xA9", "\xAE", "\u2122"]);
1516
+ var hasEmoji = (s) => [...s.matchAll(EMOJI)].some(([, ch, vs]) => vs || !TEXT_FORM_ALLOWED.has(ch));
1517
+ var LABEL_KEYS = /* @__PURE__ */ new Set(["name", "title", "label", "info", "placeholder", "description"]);
1518
+ var line = (key, errors, passed) => errors.length ? { key, status: "failed", message: errors[0].message, errors: errors.slice(0, 50) } : { key, status: "passed", message: passed, errors: [] };
1519
+ function treeOf(dir) {
1520
+ const out = [];
1521
+ const walk = (abs) => {
1522
+ for (const name of (0, import_node_fs4.readdirSync)(abs).sort()) {
1523
+ const p = (0, import_node_path4.join)(abs, name);
1524
+ if ((0, import_node_fs4.statSync)(p).isDirectory()) walk(p);
1525
+ else out.push({ path: (0, import_node_path4.relative)(dir, p).split(import_node_path4.sep).join("/"), bytes: (0, import_node_fs4.readFileSync)(p) });
1526
+ }
1527
+ };
1528
+ walk(dir);
1529
+ return out;
1530
+ }
1531
+ var failure = (e) => ({
1532
+ path: e.path?.toString() ?? "",
1533
+ code: e instanceof BuildServiceError ? String(e.kind ?? e.name) : "error",
1534
+ message: e.message
1535
+ });
1536
+ async function checkPartnerSource(tgz, built) {
1537
+ const lines = [];
1538
+ let files = [];
1539
+ try {
1540
+ files = (await extractTarballGuarded(import_node_stream.Readable.from([tgz]))).files;
1541
+ } catch (e) {
1542
+ lines.push(line("archive", [failure(e)], ""));
1543
+ }
1544
+ let ingest = null;
1545
+ try {
1546
+ ingest = new IngestGate({ mirrorHosts: [], allowlist: loadMirrorAllowlist(), thirdParty: true }).inspect(files);
1547
+ lines.push(line("ingest_gate", [], `${ingest.layout} layout, ${ingest.files.length} build input(s)`));
1548
+ } catch (e) {
1549
+ lines.push(line("ingest_gate", [failure(e)], ""));
1550
+ }
1551
+ const pkg = JSON.parse(files.find((f) => f.path === "package.json")?.bytes.toString("utf8") ?? "{}");
1552
+ const pinOf = (name) => pkg["dependencies"]?.[name] ?? pkg["devDependencies"]?.[name];
1553
+ const toolchains = JSON.parse((0, import_node_fs4.readFileSync)(THIRD_PARTY_TOOLCHAINS_PATH, "utf8"));
1554
+ const kits = loadThirdPartyKits().map((k) => k.version);
1555
+ const starterAbi = toolchains.starter?.packages?.find((p) => p.name === "@tanqory/theme-abi")?.version;
1556
+ const build = [];
1557
+ const kit = pinOf("@tanqory/theme-kit");
1558
+ if (!kit || !kits.includes(kit))
1559
+ build.push({ path: "package.json", code: "kit_not_carried", message: `package.json pins @tanqory/theme-kit ${JSON.stringify(kit ?? null)}; the builder carries ${kits.join(", ")}. Pin one of those exactly.` });
1560
+ const abi = pinOf("@tanqory/theme-abi");
1561
+ if (abi !== void 0 && ingest?.layout !== "theme-source" && abi !== starterAbi)
1562
+ build.push({ path: "package.json", code: "abi_not_carried", message: `package.json pins @tanqory/theme-abi ${JSON.stringify(abi)}; the builder's starter toolchain carries ${starterAbi}. Pin that exactly.` });
1563
+ lines.push(line("sandbox_build", build, `@tanqory/theme-kit ${kit} and @tanqory/theme-abi ${abi ?? "(not pinned)"} are carried by the builder`));
1564
+ const text = [];
1565
+ for (const f of files) {
1566
+ if (BRAND_RE.test(f.path)) text.push({ path: f.path, code: "brand_term", message: `The file name ${f.path} names another commerce platform. Rename it.` });
1567
+ else if (!f.bytes.subarray(0, 8192).includes(0)) {
1568
+ const s = f.bytes.toString("utf8");
1569
+ const i = s.search(BRAND_RE);
1570
+ if (i >= 0) {
1571
+ const at = s.slice(0, i).split("\n").length;
1572
+ text.push({ path: `${f.path}:${at}`, code: "brand_term", message: `${f.path} line ${at} names another commerce platform. Use your theme's own words.` });
1573
+ }
1574
+ }
1575
+ }
1576
+ lines.push(line("source_text", text, `${files.length} source file(s) checked`));
1577
+ if (built) {
1578
+ const out = treeOf(built);
1579
+ const manifestFile = out.find((f) => f.path === "manifest.json");
1580
+ let manifest = null;
1581
+ const mErrors = [];
1582
+ if (!manifestFile) mErrors.push({ path: "manifest.json", code: "manifest_missing", message: `The build wrote no manifest.json in ${built}.` });
1583
+ else {
1584
+ manifest = JSON.parse(manifestFile.bytes.toString("utf8"));
1585
+ const r = (0, import_theme_abi2.validateManifest)(manifest, { artifactFiles: out.map((f) => f.path) });
1586
+ if (!r.ok) for (const e of r.errors) mErrors.push({ path: e.path, code: e.code, message: e.message });
1587
+ }
1588
+ lines.push(line("manifest", mErrors, "theme-manifest v2: schema and semantic checks passed"));
1589
+ const labels = [];
1590
+ const walk = (v, path, key) => {
1591
+ if (typeof v === "string") {
1592
+ if (key !== null && LABEL_KEYS.has(key)) labels.push([path || "/", v]);
1593
+ } else if (Array.isArray(v)) v.forEach((x, i) => walk(x, `${path}/${i}`, key));
1594
+ else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) walk(x, `${path}/${k.replace(/~/g, "~0").replace(/\//g, "~1")}`, k);
1595
+ };
1596
+ walk(manifest, "", null);
1597
+ lines.push(line("manifest_brand_term", labels.filter(([, s]) => BRAND_RE.test(s)).map(([path]) => ({ path, code: "brand_term", message: `${path} names another commerce platform.` })), `${labels.length} label(s) checked`));
1598
+ lines.push(line("manifest_emoji", labels.filter(([, s]) => hasEmoji(s)).map(([path]) => ({ path, code: "emoji", message: `${path} contains an emoji.` })), `${labels.length} label(s) checked`));
1599
+ const noEval = noEvalLine(out);
1600
+ lines.push({ key: "no_eval", ...noEval });
1601
+ if (ingest) {
1602
+ const sbom = serializeSbom({
1603
+ lockfile: ingest.lockfile,
1604
+ themeName: ingest.packageJson.name,
1605
+ themeVersion: ingest.packageJson.version,
1606
+ sourceDigest: ingest.sourceDigest,
1607
+ inputDigest: sha256Digest(Buffer.from("partner-source-check"))
1608
+ });
1609
+ lines.push({ key: "licences", ...licencesLine([...out, { path: "sbom.cdx.json", bytes: sbom }], loadThemeLicences()) });
1610
+ }
1611
+ }
1612
+ return { tgzBytes: tgz.length, layout: ingest?.layout ?? null, lines };
1613
+ }
1614
+ // Annotate the CommonJS export names for ESM import in node:
1615
+ 0 && (module.exports = {
1616
+ checkPartnerSource
1617
+ });