@plasius/asset-contracts 0.6.0 → 0.7.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 +18 -0
- package/README.md +67 -1
- package/dist/index.cjs +213 -37
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +65 -2
- package/dist/index.d.ts +65 -2
- package/dist/index.js +210 -37
- package/dist/index.js.map +1 -1
- package/docs/adrs/adr-0011-reloadable-texture-resource-roles.md +92 -0
- package/docs/adrs/index.md +1 -0
- package/docs/tdrs/index.md +1 -0
- package/docs/tdrs/tdr-0006-reloadable-texture-resource-roles.md +91 -0
- package/package.json +1 -1
- package/src/index.ts +1 -0
- package/src/model-texture-resources.ts +215 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# ADR 0011: Reloadable Texture and Resource Roles
|
|
2
|
+
|
|
3
|
+
- Status: Accepted
|
|
4
|
+
- Date: 2026-10-24
|
|
5
|
+
- Tracking: asset-contracts Task 50; site Feature 1153 / Epic 1147
|
|
6
|
+
|
|
7
|
+
## Context
|
|
8
|
+
|
|
9
|
+
Released AssetFileRole already defines model, binary, texture and metadata.
|
|
10
|
+
Task 48 qualifies exact file inventory/bytes, and model-core 0.7.0 owns verified
|
|
11
|
+
resources, material-to-texture references and authored interpretation metadata.
|
|
12
|
+
Neither boundary maps the canonical inventory to storage roles or records
|
|
13
|
+
separate GPU upload/atlas exports while retaining original resource identities.
|
|
14
|
+
Legacy descriptor construction must remain compatible.
|
|
15
|
+
|
|
16
|
+
## Decision
|
|
17
|
+
|
|
18
|
+
Add opt-in async qualifyModelTextureResources. Compose the existing
|
|
19
|
+
qualifyModelResourceManifest and accept only a privately branded model-core
|
|
20
|
+
GpuModelResourceGraph. Reuse canonical materials/textures, including samplers,
|
|
21
|
+
color spaces, usages, transforms, embedding policy and authored sourceMetadata.
|
|
22
|
+
Never reimplement the canonical schemas or parse a model format here.
|
|
23
|
+
|
|
24
|
+
Use the matching module-format core guard through a normal named import. A
|
|
25
|
+
new graph is already immutable/verified. Dynamically importing ESM from the
|
|
26
|
+
CJS build would select a different private WeakSet and reject legitimate CJS
|
|
27
|
+
require-created graphs. This correctness requirement makes lazy loading this
|
|
28
|
+
guard inappropriate. Core remains external; bundlers can remove unused exports
|
|
29
|
+
with sideEffects=false. Existing diagnostic evaluation retains its dynamic
|
|
30
|
+
import. Consumers must produce graphs using the same installed core instance
|
|
31
|
+
and module format as this package (ESM import with ESM, require with CJS).
|
|
32
|
+
|
|
33
|
+
Map canonical mesh entries to model/binary, material/animation to JSON metadata,
|
|
34
|
+
texture to supported image texture, and auxiliary to binary or JSON metadata.
|
|
35
|
+
Existing role values are unchanged. Explicit source bindings match every graph
|
|
36
|
+
resource exactly once. External files match graph path/hash/length/MIME;
|
|
37
|
+
embedded resources retain independent identity and name their owning model
|
|
38
|
+
entrypoint. Do not invent separate embedded archive entries or replace source
|
|
39
|
+
hashes with entrypoint hashes. Preserve original conversion provenance.
|
|
40
|
+
|
|
41
|
+
A derived record has gpu-upload or texture-atlas semantics, a distinct exported
|
|
42
|
+
file path and unique original sourceResourceIds. Uploads use auxiliary/binary
|
|
43
|
+
buffer files; atlases use texture/image files and image sources. Reject missing
|
|
44
|
+
sources, output collisions, source overwrite, unknown roles and incompatible
|
|
45
|
+
MIME declarations. Output is frozen deterministic version-1 JSON with no Blob
|
|
46
|
+
or renderer allocation. Canonical material/texture arrays retain their order.
|
|
47
|
+
|
|
48
|
+
## Limits and trust
|
|
49
|
+
|
|
50
|
+
Snapshot caller metadata and exact bytes before awaiting. Reuse Task 48 path,
|
|
51
|
+
collision, byte/hash and inventory gates. Apply fixed resource/derived/graph,
|
|
52
|
+
metadata value/character/depth and deadline limits. Honor native cancellation;
|
|
53
|
+
use no I/O, retries, mutable registry, arbitrary callbacks or logging. Hashing
|
|
54
|
+
cannot be interrupted inside Web Crypto; checks prevent successful late return.
|
|
55
|
+
Errors expose fixed codes only. Synchronous bounded work is checked before and
|
|
56
|
+
after; it cannot be preempted by a JavaScript timer.
|
|
57
|
+
|
|
58
|
+
Authored sourceMetadata, material names/extensions and original texture paths
|
|
59
|
+
are deliberately preserved trusted package content. The output is NOT a
|
|
60
|
+
public-safe diagnostics response. Adapters must minimize/sanitize authored
|
|
61
|
+
metadata before public distribution; use Task 49's separate diagnostic
|
|
62
|
+
projection for public technical messages. Core-brand validation cannot be
|
|
63
|
+
replaced by shape checks or serialization; reloaded canonical payloads must be
|
|
64
|
+
verified again by core before a new graph is created.
|
|
65
|
+
|
|
66
|
+
Embedded ownership, internal model references and derivation algorithms remain
|
|
67
|
+
trusted adapter assertions. Exact byte qualification does not prove semantic
|
|
68
|
+
format validity, inspect derived image signatures, verify a GPU upload layout,
|
|
69
|
+
attest an atlas algorithm, or authorize promotion. Tasks 12/23/51 retain
|
|
70
|
+
animation metadata, shader ABI and promotion closure. No existing approval gate
|
|
71
|
+
changes. No dependency/version/peer/override changes are required.
|
|
72
|
+
|
|
73
|
+
## Alternatives, rollout and delivery
|
|
74
|
+
|
|
75
|
+
Adding storage role enums would duplicate existing roles and break closed
|
|
76
|
+
consumers. Tightening legacy factories would break staged construction.
|
|
77
|
+
Flattening derived output over authored textures would lose reload fidelity.
|
|
78
|
+
Copying core schemas or accepting a structural graph would discard verification.
|
|
79
|
+
|
|
80
|
+
The backend evaluator for gpu.model.conversion.enabled controls consumer
|
|
81
|
+
adoption. Enabled callers opt into this qualifier; disabled/rollback callers
|
|
82
|
+
retain existing factories. The library performs no flag lookup/mutation. No UI
|
|
83
|
+
or entitlement capability applies. Test both branches and rollback.
|
|
84
|
+
|
|
85
|
+
Require requirements-first round-trip/contract tests, malformed input/role/MIME
|
|
86
|
+
and missing/duplicate identity cases, deterministic/frozen output, cancellation,
|
|
87
|
+
deadline and bounded metadata tests. Run Node 24 frozen install, full tests and
|
|
88
|
+
privacy, coverage >=80% and changed-source LCOV, lint/types/build, audits/tree,
|
|
89
|
+
privacy/pack and packed/public ESM/CJS/types/browser consumers. Release additive
|
|
90
|
+
minor through source PR, exact-main push CI and existing two-phase
|
|
91
|
+
cd.yml/main/production hosted OIDC governance (ADR 0007), then verify registry
|
|
92
|
+
integrity/provenance. Site adoption/deployment remains separate.
|
package/docs/adrs/index.md
CHANGED
|
@@ -10,3 +10,4 @@
|
|
|
10
10
|
- [ADR 0008: Package-Owned Issue Tracking](./adr-0008-package-owned-issue-tracking.md)
|
|
11
11
|
- [ADR 0009: Additive Model Resource Manifest Qualification](./adr-0009-model-resource-manifest-qualification.md)
|
|
12
12
|
- [ADR 0010: Public Conversion Diagnostics](./adr-0010-public-conversion-diagnostics.md)
|
|
13
|
+
- [ADR 0011: Reloadable Texture and Resource Roles](./adr-0011-reloadable-texture-resource-roles.md)
|
package/docs/tdrs/index.md
CHANGED
|
@@ -5,3 +5,4 @@
|
|
|
5
5
|
- [TDR 0003: PVOX Validation and Confirmation Binding](./tdr-0003-pvox-validation-and-confirmation-binding.md)
|
|
6
6
|
- [TDR 0004: Model Resource Manifest Qualification](./tdr-0004-model-resource-manifest-qualification.md)
|
|
7
7
|
- [TDR 0005: Public Conversion Diagnostics](./tdr-0005-public-conversion-diagnostics.md)
|
|
8
|
+
- [TDR 0006: Reloadable Texture and Resource Qualification](./tdr-0006-reloadable-texture-resource-roles.md)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# TDR 0006: Reloadable Texture and Resource Qualification
|
|
2
|
+
|
|
3
|
+
- Status: Accepted
|
|
4
|
+
- Date: 2026-10-24
|
|
5
|
+
- Tracking: asset-contracts Task 50; site Feature 1153
|
|
6
|
+
- Decision: ADR 0011
|
|
7
|
+
|
|
8
|
+
## Sequence and role policy
|
|
9
|
+
|
|
10
|
+
1. Read inert root/options records without executing getters. Verify the graph
|
|
11
|
+
with the matching ESM/CJS core instance's private brand, not a shape cast.
|
|
12
|
+
2. Snapshot inventory, resource bindings and derived records with shared fixed
|
|
13
|
+
budgets before awaiting. Reject unknown fields, accessors, symbols, prototype
|
|
14
|
+
keys, sparse/exotic arrays, non-finite values and malformed IDs.
|
|
15
|
+
3. Invoke existing qualifyModelResourceManifest, which synchronously snapshots
|
|
16
|
+
manifest metadata and all bounded exact byte payloads before its first hash.
|
|
17
|
+
Race the operation against native cancellation/deadline and clean listeners.
|
|
18
|
+
4. Map every inventory entry to an existing storage role and MIME policy:
|
|
19
|
+
|
|
20
|
+
| Canonical role | Storage role | MIME policy |
|
|
21
|
+
| --- | --- | --- |
|
|
22
|
+
| mesh | model | model/*, application/json, application/octet-stream, text/plain |
|
|
23
|
+
| mesh | binary | application/octet-stream, application/vnd.plasius.gpu-buffer |
|
|
24
|
+
| material or animation | metadata | application/json |
|
|
25
|
+
| texture | texture | image/png, image/jpeg, image/webp, image/ktx2 |
|
|
26
|
+
| auxiliary | binary or metadata | buffer MIME for binary; application/json for metadata |
|
|
27
|
+
|
|
28
|
+
5. Require exactly one binding per graph resource. For external resources,
|
|
29
|
+
compare exact graph path, verified content hash/length/MIME and appropriate
|
|
30
|
+
image/buffer role. Embedded resources bind only the model entrypoint and
|
|
31
|
+
retain their independent hash/length/MIME rather than the container's hash.
|
|
32
|
+
6. Validate each derived output's distinct existing file and original source
|
|
33
|
+
IDs. gpu-upload requires auxiliary/binary with buffer MIME. texture-atlas
|
|
34
|
+
requires texture with image MIME and image sources. Never overwrite a bound
|
|
35
|
+
source file or reassign a source identity to derived bytes. Multiple authored
|
|
36
|
+
texture interpretations may share one original image resource.
|
|
37
|
+
7. Bound canonical authored material/texture/provenance metadata, retain its
|
|
38
|
+
already immutable values and emit JSON without Blob payloads. Sort resource
|
|
39
|
+
bindings by resourceId, derivatives by path and source-ID sets by UTF-16
|
|
40
|
+
code units. Preserve canonical array order and original provenance.
|
|
41
|
+
|
|
42
|
+
This is declarative role qualification, not a parser, MIME sniffer, GPU-layout
|
|
43
|
+
validator or promotion attestation. Derived records are optional (empty array);
|
|
44
|
+
caller-declared derivation/embedding is not cryptographic algorithm evidence.
|
|
45
|
+
|
|
46
|
+
## Fixed limits and errors
|
|
47
|
+
|
|
48
|
+
Resource bindings: 16,384; derived records: 4,096; core graph nodes: 65,536.
|
|
49
|
+
Shared metadata budgets: 262,144 values, 2,097,152 UTF-16 characters, depth 16,
|
|
50
|
+
2,048 characters/string and 128/key; arrays at most 16,384. IDs use 128-character
|
|
51
|
+
canonical tokens. The existing byte qualifier also applies its own limits:
|
|
52
|
+
16,384 files, 64 MiB/file, 128 MiB total and portable-path rules. Default deadline
|
|
53
|
+
10 seconds, configurable integer 1–60,000 ms. Cancellation/timer cover the
|
|
54
|
+
async boundary and checks surround bounded synchronous phases. Web Crypto work
|
|
55
|
+
cannot be interrupted but never yields a successful result after cancellation
|
|
56
|
+
or expiry. Work is sequential and introduces no retry or storage/network I/O.
|
|
57
|
+
|
|
58
|
+
ModelTextureResourceError exposes invalid-input, limit-exceeded,
|
|
59
|
+
unverified-graph, package-mismatch, resource-mismatch, role-mismatch, aborted or
|
|
60
|
+
deadline-exceeded. Upstream errors are normalized without caller values.
|
|
61
|
+
|
|
62
|
+
## Verification, rollout and limitations
|
|
63
|
+
|
|
64
|
+
Synthetic fixtures independently verify core image/buffer bytes; canonical
|
|
65
|
+
material references require a real UV accessor. Compare external hashes and
|
|
66
|
+
reloaded material JSON with core metadata; serialize and reconstruct canonical
|
|
67
|
+
materials/textures, then verify core accepts the reloaded document. An embedded
|
|
68
|
+
image fixture uses an actual data URI without a fictitious exported source
|
|
69
|
+
image. Derivative hashes differ from the source identity. Test duplicate/missing
|
|
70
|
+
resources, role/MIME drift, unknown roles, graph clone rejection, multiple
|
|
71
|
+
interpretations, getters/proxies, mutation isolation, limits, deadline/abort and
|
|
72
|
+
legacy enabled/disabled/rollback composition. Qualify both typed model and
|
|
73
|
+
legacy envelopes; do not modify shader ABI or animation schemas.
|
|
74
|
+
|
|
75
|
+
Trusted authored sourceMetadata is intentionally preserved; callers own privacy
|
|
76
|
+
minimization before distribution. Public diagnostics use the separate Task 49
|
|
77
|
+
projection. UI accessibility/SEO/browser UI and durable storage controls are N/A
|
|
78
|
+
here. Security/privacy: value-free failures, bounded inert input and exact bytes.
|
|
79
|
+
Performance/reliability: fixed budgets, sequential hashing, no GPU allocation,
|
|
80
|
+
I/O or retry. Maintainability/testability: existing schemas/qualifier reuse and
|
|
81
|
+
immutable deterministic JSON. Compatibility: additive API, unchanged legacy
|
|
82
|
+
factories, dependency versions and existing approval gates.
|
|
83
|
+
|
|
84
|
+
The source-of-truth backend evaluator gpu.model.conversion.enabled controls
|
|
85
|
+
adoption. Disable/rollback retains legacy factories; no service call or mutation
|
|
86
|
+
inside this package and capability N/A. Normal module-format core guard import
|
|
87
|
+
preserves private brand identity across ESM/CJS. Verify packed/public ESM/CJS
|
|
88
|
+
consumers with their matching core entry and browser bundling/execution. Release
|
|
89
|
+
through existing PR/exact-main CI/cd.yml/production hosted OIDC route, verify
|
|
90
|
+
public registry integrity/provenance and dependency signatures. No site release
|
|
91
|
+
or backend secretref mutation is authorized by this Task.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plasius/asset-contracts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Canonical contracts for Plasius asset jobs, model resolution, immutable WGSL shader assets, reviews, and promotion records.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
package/src/index.ts
CHANGED
|
@@ -39,6 +39,7 @@ export * from "./pvox-hash-preimage.js";
|
|
|
39
39
|
export * from "./pvox-model-resolution.js";
|
|
40
40
|
export * from "./pvox-model-resolution-schema.js";
|
|
41
41
|
export * from "./model-resource-manifest.js";
|
|
42
|
+
export * from "./model-texture-resources.js";
|
|
42
43
|
export * from "./model-conversion-diagnostics.js";
|
|
43
44
|
export {
|
|
44
45
|
GPU_SHADER_STORE_FEATURE_FLAG,
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { isGpuModelResourceGraph } from "@plasius/gpu-model-core";
|
|
2
|
+
import type {
|
|
3
|
+
GpuModelMaterial, GpuModelTexture, GpuModelProvenance, GpuModelResourceGraph,
|
|
4
|
+
GpuModelResourceLocation, GpuModelTextureEmbeddingPolicy,
|
|
5
|
+
} from "@plasius/gpu-model-core";
|
|
6
|
+
import { qualifyModelResourceManifest, ModelResourceManifestError, type ModelResourceManifestQualificationInput } from "./model-resource-manifest.js";
|
|
7
|
+
import type { AssetManifest, AssetFileDescriptor } from "./index.js";
|
|
8
|
+
|
|
9
|
+
/** Hard ceilings for the additive package role boundary; callers cannot raise them. */
|
|
10
|
+
export const MODEL_TEXTURE_RESOURCE_LIMITS = Object.freeze({ resources: 16_384, derived: 4096, nodes: 65_536, values: 262_144, characters: 2_097_152, depth: 16, timeoutMs: 60_000 });
|
|
11
|
+
/** An embedded resource names its owning entrypoint; external resources name their exact graph path. */
|
|
12
|
+
export interface ModelTextureResourceBinding { readonly resourceId: string; readonly filePath: string }
|
|
13
|
+
/** Declarative derived output; source identities remain independent of output hashes and paths. */
|
|
14
|
+
export interface ModelDerivedTextureResource {
|
|
15
|
+
readonly role: "gpu-upload" | "texture-atlas";
|
|
16
|
+
readonly filePath: string;
|
|
17
|
+
readonly sourceResourceIds: readonly string[];
|
|
18
|
+
}
|
|
19
|
+
/** Existing exact-byte inventory plus a privately verified canonical graph and explicit export bindings. */
|
|
20
|
+
export interface ModelTextureResourceQualificationInput extends Omit<ModelResourceManifestQualificationInput, "signal" | "timeoutMs"> {
|
|
21
|
+
readonly graph: GpuModelResourceGraph;
|
|
22
|
+
readonly resources: readonly ModelTextureResourceBinding[];
|
|
23
|
+
readonly derived: readonly ModelDerivedTextureResource[];
|
|
24
|
+
}
|
|
25
|
+
/** Deadline and cancellation cover hashing and bounded synchronous qualification. */
|
|
26
|
+
export interface ModelTextureResourceQualificationOptions { readonly signal?: AbortSignal; readonly timeoutMs?: number }
|
|
27
|
+
/** JSON resource identity without a Blob, renderer allocation or credential-bearing URL. */
|
|
28
|
+
export interface QualifiedModelTextureResource extends ModelTextureResourceBinding {
|
|
29
|
+
readonly kind: "image" | "buffer";
|
|
30
|
+
readonly contentHash: string;
|
|
31
|
+
readonly byteLength: number;
|
|
32
|
+
readonly mimeType: string;
|
|
33
|
+
readonly location: GpuModelResourceLocation;
|
|
34
|
+
readonly exportEmbeddingPolicy: GpuModelTextureEmbeddingPolicy;
|
|
35
|
+
}
|
|
36
|
+
/** Trusted package metadata, including authored sourceMetadata; not a public-safe diagnostic projection. */
|
|
37
|
+
export interface QualifiedModelTextureResources {
|
|
38
|
+
readonly contractVersion: 1;
|
|
39
|
+
readonly manifest: AssetManifest;
|
|
40
|
+
readonly source: GpuModelProvenance;
|
|
41
|
+
readonly resources: readonly QualifiedModelTextureResource[];
|
|
42
|
+
readonly materials: readonly GpuModelMaterial[];
|
|
43
|
+
readonly textures: readonly GpuModelTexture[];
|
|
44
|
+
readonly derived: readonly ModelDerivedTextureResource[];
|
|
45
|
+
}
|
|
46
|
+
/** Fixed, value-free errors. No caller metadata or upstream exception text is exposed. */
|
|
47
|
+
export class ModelTextureResourceError extends TypeError {
|
|
48
|
+
constructor(public readonly code: "invalid-input" | "limit-exceeded" | "unverified-graph" | "package-mismatch" | "resource-mismatch" | "role-mismatch" | "aborted" | "deadline-exceeded") {
|
|
49
|
+
super(`Invalid model texture resources: ${code}`); this.name = "ModelTextureResourceError";
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function fail(code: ModelTextureResourceError["code"] = "invalid-input"): never { throw new ModelTextureResourceError(code); }
|
|
53
|
+
function fields(value: unknown, allowed?: readonly string[]): Record<string, unknown> {
|
|
54
|
+
if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) fail();
|
|
55
|
+
const keys = Reflect.ownKeys(value);
|
|
56
|
+
if (keys.length > 1024) fail("limit-exceeded");
|
|
57
|
+
const result: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
|
|
58
|
+
for (const key of keys) {
|
|
59
|
+
if (typeof key !== "string" || key.length > 128 || ["__proto__", "prototype", "constructor"].includes(key) || (allowed && !allowed.includes(key))) fail();
|
|
60
|
+
const property = Object.getOwnPropertyDescriptor(value, key)!;
|
|
61
|
+
if (!("value" in property) || !property.enumerable) fail();
|
|
62
|
+
result[key] = property.value;
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
function array(value: unknown, maximum: number): unknown[] {
|
|
67
|
+
if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype) fail();
|
|
68
|
+
if (value.length > maximum) fail("limit-exceeded");
|
|
69
|
+
if (Reflect.ownKeys(value).length !== value.length + 1) fail();
|
|
70
|
+
const result: unknown[] = [];
|
|
71
|
+
for (let i = 0; i < value.length; i++) {
|
|
72
|
+
const property = Object.getOwnPropertyDescriptor(value, String(i));
|
|
73
|
+
if (!property || !("value" in property) || !property.enumerable) fail();
|
|
74
|
+
result.push(property.value);
|
|
75
|
+
}
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
function snapshot(value: unknown, budget: { values: number; characters: number }, depth = 0): unknown {
|
|
79
|
+
if (--budget.values < 0 || depth > MODEL_TEXTURE_RESOURCE_LIMITS.depth) fail("limit-exceeded");
|
|
80
|
+
if (value === null || value === undefined || typeof value === "boolean") return value;
|
|
81
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
82
|
+
if (typeof value === "string") {
|
|
83
|
+
budget.characters -= value.length;
|
|
84
|
+
if (value.length > 2048 || budget.characters < 0) fail("limit-exceeded");
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
if (Array.isArray(value)) return Object.freeze(array(value, MODEL_TEXTURE_RESOURCE_LIMITS.resources).map((v) => snapshot(v, budget, depth + 1)));
|
|
88
|
+
const result = fields(value);
|
|
89
|
+
for (const key of Object.keys(result)) {
|
|
90
|
+
budget.characters -= key.length;
|
|
91
|
+
if (budget.characters < 0) fail("limit-exceeded");
|
|
92
|
+
result[key] = snapshot(result[key], budget, depth + 1);
|
|
93
|
+
}
|
|
94
|
+
return Object.freeze(result);
|
|
95
|
+
}
|
|
96
|
+
function token(value: unknown): string {
|
|
97
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u.test(value)) fail();
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
const compare = (a: string, b: string): number => a < b ? -1 : a > b ? 1 : 0;
|
|
101
|
+
const imageMime = (value: string): boolean => ["image/png", "image/jpeg", "image/webp", "image/ktx2"].includes(value);
|
|
102
|
+
const bufferMime = (value: string): boolean => ["application/octet-stream", "application/vnd.plasius.gpu-buffer"].includes(value);
|
|
103
|
+
function storageRole(role: unknown, file: AssetFileDescriptor): void {
|
|
104
|
+
const valid = role === "texture" ? file.role === "texture" && imageMime(file.contentType)
|
|
105
|
+
: role === "material" || role === "animation" ? file.role === "metadata" && file.contentType === "application/json"
|
|
106
|
+
: role === "mesh" ? (file.role === "binary" && bufferMime(file.contentType)) || (file.role === "model" && (file.contentType.startsWith("model/") || ["application/json", "application/octet-stream", "text/plain"].includes(file.contentType)))
|
|
107
|
+
: role === "auxiliary" && ((file.role === "binary" && bufferMime(file.contentType)) || (file.role === "metadata" && file.contentType === "application/json"));
|
|
108
|
+
if (!valid) fail("role-mismatch");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Qualify reload metadata without parsing formats, allocating GPU objects or
|
|
113
|
+
* replacing authored resource identities. Metadata is trusted package content;
|
|
114
|
+
* adapters must sanitize it before public use. This is not promotion evidence.
|
|
115
|
+
*/
|
|
116
|
+
export async function qualifyModelTextureResources(input: ModelTextureResourceQualificationInput, options: ModelTextureResourceQualificationOptions = {}): Promise<QualifiedModelTextureResources> {
|
|
117
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
118
|
+
let signal: AbortSignal | undefined;
|
|
119
|
+
let onAbort: (() => void) | undefined;
|
|
120
|
+
try {
|
|
121
|
+
const started = performance.now();
|
|
122
|
+
const controls = fields(options, ["signal", "timeoutMs"]);
|
|
123
|
+
const timeoutMs = controls.timeoutMs === undefined ? 10_000 : controls.timeoutMs;
|
|
124
|
+
if (typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MODEL_TEXTURE_RESOURCE_LIMITS.timeoutMs) fail();
|
|
125
|
+
signal = controls.signal as AbortSignal | undefined;
|
|
126
|
+
const aborted = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted")!.get!;
|
|
127
|
+
const check = () => {
|
|
128
|
+
if (signal !== undefined && aborted.call(signal)) fail("aborted");
|
|
129
|
+
if (performance.now() - started >= timeoutMs) fail("deadline-exceeded");
|
|
130
|
+
};
|
|
131
|
+
check();
|
|
132
|
+
const root = fields(input, ["manifest", "packageManifest", "files", "graph", "resources", "derived"]);
|
|
133
|
+
const graph = root.graph;
|
|
134
|
+
if (!isGpuModelResourceGraph(graph)) fail("unverified-graph");
|
|
135
|
+
if (graph.nodes.length > MODEL_TEXTURE_RESOURCE_LIMITS.nodes) fail("limit-exceeded");
|
|
136
|
+
const budget = { values: MODEL_TEXTURE_RESOURCE_LIMITS.values, characters: MODEL_TEXTURE_RESOURCE_LIMITS.characters };
|
|
137
|
+
const inventory = snapshot(root.packageManifest, budget) as ModelResourceManifestQualificationInput["packageManifest"];
|
|
138
|
+
const bindings = array(snapshot(root.resources, budget), MODEL_TEXTURE_RESOURCE_LIMITS.resources).map((value) => {
|
|
139
|
+
const binding = fields(value, ["resourceId", "filePath"]);
|
|
140
|
+
return Object.freeze({ resourceId: token(binding.resourceId), filePath: tokenPath(binding.filePath) });
|
|
141
|
+
});
|
|
142
|
+
const derived = array(snapshot(root.derived, budget), MODEL_TEXTURE_RESOURCE_LIMITS.derived).map((value) => {
|
|
143
|
+
const record = fields(value, ["role", "filePath", "sourceResourceIds"]);
|
|
144
|
+
if (record.role !== "gpu-upload" && record.role !== "texture-atlas") fail("role-mismatch");
|
|
145
|
+
const ids = array(record.sourceResourceIds, MODEL_TEXTURE_RESOURCE_LIMITS.resources).map(token);
|
|
146
|
+
if (!ids.length || new Set(ids).size !== ids.length) fail("resource-mismatch");
|
|
147
|
+
return Object.freeze({ role: record.role, filePath: tokenPath(record.filePath), sourceResourceIds: Object.freeze(ids.sort(compare)) });
|
|
148
|
+
});
|
|
149
|
+
check();
|
|
150
|
+
const interrupted = new Promise<never>((_resolve, reject) => {
|
|
151
|
+
timer = setTimeout(() => reject(new ModelTextureResourceError("deadline-exceeded")), Math.max(1, timeoutMs - (performance.now() - started)));
|
|
152
|
+
onAbort = () => reject(new ModelTextureResourceError("aborted"));
|
|
153
|
+
if (signal) AbortSignal.prototype.addEventListener.call(signal, "abort", onAbort, { once: true });
|
|
154
|
+
});
|
|
155
|
+
// The existing qualifier snapshots metadata AND byte payloads synchronously
|
|
156
|
+
// before its first digest. Promise.race owns both rejection paths immediately.
|
|
157
|
+
const manifest = await Promise.race([
|
|
158
|
+
qualifyModelResourceManifest({ manifest: root.manifest as AssetManifest, files: root.files as ModelResourceManifestQualificationInput["files"], packageManifest: inventory, signal, timeoutMs }),
|
|
159
|
+
interrupted,
|
|
160
|
+
]);
|
|
161
|
+
check();
|
|
162
|
+
const files = new Map(manifest.files.map((file) => [file.path, file]));
|
|
163
|
+
const roles = new Map(inventory.entries.map((entry) => [entry.path, entry.role]));
|
|
164
|
+
for (const entry of inventory.entries) storageRole(entry.role, files.get(entry.path)!);
|
|
165
|
+
const resources = new Map(graph.nodes.filter((node) => node.kind === "resource").map((node) => [node.id, node.value]));
|
|
166
|
+
if (bindings.length !== resources.size || new Set(bindings.map((b) => b.resourceId)).size !== bindings.length) fail("resource-mismatch");
|
|
167
|
+
const resourceFiles = new Set<string>();
|
|
168
|
+
const qualified = bindings.map((binding): QualifiedModelTextureResource => {
|
|
169
|
+
const value = resources.get(binding.resourceId); const file = files.get(binding.filePath);
|
|
170
|
+
if (!value || !file) fail("resource-mismatch");
|
|
171
|
+
const { resource, location, exportEmbeddingPolicy } = value;
|
|
172
|
+
if (location.kind === "external") {
|
|
173
|
+
if (binding.filePath !== location.relativePath || file.sha256 !== resource.contentHash || file.byteLength !== resource.byteLength || file.contentType !== resource.mimeType) fail("resource-mismatch");
|
|
174
|
+
if (resource.kind === "image" ? roles.get(file.path) !== "texture" : file.role !== "binary") fail("role-mismatch");
|
|
175
|
+
} else if (binding.filePath !== manifest.entrypoint || file.role !== "model") fail("resource-mismatch");
|
|
176
|
+
resourceFiles.add(binding.filePath);
|
|
177
|
+
return Object.freeze({ ...binding, kind: resource.kind, contentHash: resource.contentHash, byteLength: resource.byteLength, mimeType: resource.mimeType, location, exportEmbeddingPolicy });
|
|
178
|
+
});
|
|
179
|
+
const outputFiles = new Set<string>();
|
|
180
|
+
for (const output of derived) {
|
|
181
|
+
const file = files.get(output.filePath);
|
|
182
|
+
if (!file || outputFiles.has(output.filePath) || resourceFiles.has(output.filePath)) fail("resource-mismatch");
|
|
183
|
+
outputFiles.add(output.filePath);
|
|
184
|
+
for (const id of output.sourceResourceIds) {
|
|
185
|
+
const source = resources.get(id);
|
|
186
|
+
if (!source || (output.role === "texture-atlas" && source.resource.kind !== "image")) fail("resource-mismatch");
|
|
187
|
+
}
|
|
188
|
+
if (output.role === "gpu-upload" ? file.role !== "binary" || !bufferMime(file.contentType) || roles.get(file.path) !== "auxiliary"
|
|
189
|
+
: file.role !== "texture" || !imageMime(file.contentType) || roles.get(file.path) !== "texture") fail("role-mismatch");
|
|
190
|
+
}
|
|
191
|
+
const materials = graph.nodes.filter((node) => node.kind === "material").map((node) => node.value);
|
|
192
|
+
const textures = graph.nodes.filter((node) => node.kind === "texture").map((node) => node.value);
|
|
193
|
+
const source = graph.nodes.find((node) => node.kind === "provenance")!;
|
|
194
|
+
if (source.kind !== "provenance") fail();
|
|
195
|
+
// Bound authored metadata without substituting a new material/texture schema.
|
|
196
|
+
snapshot({ materials, textures, source: source.value }, budget);
|
|
197
|
+
check();
|
|
198
|
+
return Object.freeze({ contractVersion: 1, manifest, source: source.value,
|
|
199
|
+
resources: Object.freeze(qualified.sort((a, b) => compare(a.resourceId, b.resourceId))),
|
|
200
|
+
materials: Object.freeze(materials), textures: Object.freeze(textures),
|
|
201
|
+
derived: Object.freeze(derived.sort((a, b) => compare(a.filePath, b.filePath))) });
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (error instanceof ModelTextureResourceError) throw error;
|
|
204
|
+
if (error instanceof ModelResourceManifestError) return fail(error.code === "aborted" || error.code === "deadline-exceeded" || error.code === "limit-exceeded" ? error.code : "package-mismatch");
|
|
205
|
+
return fail();
|
|
206
|
+
} finally {
|
|
207
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
208
|
+
if (signal && onAbort) AbortSignal.prototype.removeEventListener.call(signal, "abort", onAbort);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
function tokenPath(value: unknown): string {
|
|
212
|
+
// Full portable-path and collision checks are reused from the byte qualifier.
|
|
213
|
+
if (typeof value !== "string" || !value.length || value.length > 1024) fail();
|
|
214
|
+
return value;
|
|
215
|
+
}
|