@codemem/embeddings 0.47.5 → 0.48.1
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/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +44 -38
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -21,5 +21,11 @@ export interface EmbeddingClient {
|
|
|
21
21
|
embed(texts: string[]): Promise<Float32Array[]>;
|
|
22
22
|
}
|
|
23
23
|
export type EmbeddingRuntimeFactory = (request: EmbeddingRuntimeRequest) => Promise<EmbeddingClient | null>;
|
|
24
|
+
/**
|
|
25
|
+
* Directory for downloaded model files. Transformers.js defaults to a .cache
|
|
26
|
+
* directory inside its own package, which a global npm install leaves owned by
|
|
27
|
+
* root (unwritable for a non-root container user) and an upgrade replaces.
|
|
28
|
+
*/
|
|
29
|
+
export declare function resolveEmbeddingCacheDir(env?: NodeJS.ProcessEnv): string;
|
|
24
30
|
export declare function createEmbeddingRuntime({ model, revision: revisionRequest, }: EmbeddingRuntimeRequest): Promise<EmbeddingClient>;
|
|
25
31
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,uBAAuB;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,wBAAwB;IACxC,QAAQ,CAAC,OAAO,EAAE,2BAA2B,CAAC;IAC9C,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,aAAa,EAAE,IAAI,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,eAAe;IAC/B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,wBAAwB,CAAC;IAC5C,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC;CAChD;AAED,MAAM,MAAM,uBAAuB,GAAG,CACrC,OAAO,EAAE,uBAAuB,KAC5B,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAAC;AAiCrC;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,MAAM,CAQrF;AA8FD,wBAAsB,sBAAsB,CAAC,EAC5C,KAAK,EACL,QAAQ,EAAE,eAAe,GACzB,EAAE,uBAAuB,GAAG,OAAO,CAAC,eAAe,CAAC,CAgEpD"}
|
package/dist/index.js
CHANGED
|
@@ -1,29 +1,35 @@
|
|
|
1
|
+
import { homedir as e } from "node:os";
|
|
2
|
+
import { join as t } from "node:path";
|
|
1
3
|
//#region src/index.ts
|
|
2
|
-
var
|
|
3
|
-
function
|
|
4
|
+
var n = "Xenova/bge-small-en-v1.5", r = "ea104dacec62c0de699686887e3f920caeb4f3e3", i = /^[0-9a-f]{40}$/, a;
|
|
5
|
+
function o() {
|
|
4
6
|
let e = process.env.CODEMEM_EMBEDDING_OFFLINE?.toLowerCase();
|
|
5
7
|
return e === "1" || e === "true" || e === "yes";
|
|
6
8
|
}
|
|
7
|
-
function
|
|
8
|
-
if (
|
|
9
|
-
|
|
9
|
+
function s(e) {
|
|
10
|
+
if (o()) {
|
|
11
|
+
a ??= e.allowRemoteModels, e.allowRemoteModels = !1;
|
|
10
12
|
return;
|
|
11
13
|
}
|
|
12
|
-
|
|
14
|
+
a !== void 0 && (e.allowRemoteModels = a, a = void 0);
|
|
13
15
|
}
|
|
14
|
-
function
|
|
16
|
+
function c(n = process.env) {
|
|
17
|
+
let r = n.HOME?.trim() || e(), i = n.CODEMEM_EMBEDDING_CACHE_DIR?.trim();
|
|
18
|
+
return i ? i === "~" ? r : i.startsWith("~/") ? t(r, i.slice(2)) : i : t(r, ".codemem", "models");
|
|
19
|
+
}
|
|
20
|
+
function l(e) {
|
|
15
21
|
return e.startsWith(".") || e.startsWith("/") || e.startsWith("~") || e.includes("\\") || e.split("/").length > 2;
|
|
16
22
|
}
|
|
17
|
-
function
|
|
18
|
-
if ((
|
|
23
|
+
function u(e, t, a) {
|
|
24
|
+
if ((e !== n || t !== r) && !(t && i.test(t) && (l(e) || !a))) return t;
|
|
19
25
|
}
|
|
20
|
-
async function
|
|
21
|
-
let
|
|
26
|
+
async function d(e, t, n) {
|
|
27
|
+
let r = n.remotePathTemplate.replaceAll("{model}", e.split("/").map(encodeURIComponent).join("/")).replaceAll("{revision}", encodeURIComponent(t)), a = `${n.remoteHost.replace(/\/+$/, "")}/${r.replace(/^\/+|\/+$/g, "")}/config.json`, o = new Headers(), s = new URL(a).hostname;
|
|
22
28
|
if (s === "huggingface.co" || s === "hf.co") {
|
|
23
29
|
let e = process.env.HF_TOKEN ?? process.env.HF_ACCESS_TOKEN;
|
|
24
30
|
e && o.set("Authorization", `Bearer ${e}`);
|
|
25
31
|
}
|
|
26
|
-
let c = await
|
|
32
|
+
let c = await n.fetch(a, {
|
|
27
33
|
method: "HEAD",
|
|
28
34
|
redirect: "follow",
|
|
29
35
|
headers: o,
|
|
@@ -31,10 +37,10 @@ async function c(e, t, r) {
|
|
|
31
37
|
});
|
|
32
38
|
if (!c.ok) throw TypeError(`Unable to resolve Hugging Face model ${e}@${t}: HTTP ${c.status}`);
|
|
33
39
|
let l = c.headers.get("x-repo-commit")?.trim().toLowerCase();
|
|
34
|
-
if (!l || !
|
|
40
|
+
if (!l || !i.test(l)) throw TypeError(`Hugging Face did not return a canonical commit for model ${e}@${t}`);
|
|
35
41
|
return l;
|
|
36
42
|
}
|
|
37
|
-
function
|
|
43
|
+
function f(e, t, n) {
|
|
38
44
|
if (e.dims?.length !== 2 || e.dims?.length === 2 && (e.dims[0] !== t || e.dims[1] !== n) || e.data.length !== t * n) throw TypeError("Embedding model returned an invalid tensor shape or value count");
|
|
39
45
|
let r = Array.from({ length: t }, () => new Float32Array(n));
|
|
40
46
|
for (let t = 0; t < e.data.length; t++) {
|
|
@@ -46,52 +52,52 @@ function l(e, t, n) {
|
|
|
46
52
|
}
|
|
47
53
|
return r;
|
|
48
54
|
}
|
|
49
|
-
async function
|
|
50
|
-
let i =
|
|
51
|
-
if (
|
|
52
|
-
let { env:
|
|
53
|
-
a(
|
|
54
|
-
let
|
|
55
|
-
if (
|
|
56
|
-
if (
|
|
57
|
-
if (
|
|
58
|
-
else throw TypeError(`Cannot resolve mutable embedding revision ${
|
|
55
|
+
async function p({ model: e, revision: t }) {
|
|
56
|
+
let i = t?.trim();
|
|
57
|
+
if (e !== n && !i) throw TypeError("A revision is required when creating a runtime for a custom model");
|
|
58
|
+
let { env: a, pipeline: o } = await import("@huggingface/transformers");
|
|
59
|
+
a.cacheDir = c(), s(a);
|
|
60
|
+
let p = i || r, m = p, h = u(e, i, a.allowRemoteModels);
|
|
61
|
+
if (h) {
|
|
62
|
+
if (l(e)) throw TypeError("Local embedding models require a 40-character revision identity");
|
|
63
|
+
if (a.allowRemoteModels) m = await d(e, h, a);
|
|
64
|
+
else throw TypeError(`Cannot resolve mutable embedding revision ${h} while remote models are disabled`);
|
|
59
65
|
}
|
|
60
|
-
let
|
|
61
|
-
revision:
|
|
66
|
+
let g = await o("feature-extraction", e, {
|
|
67
|
+
revision: m,
|
|
62
68
|
device: "cpu",
|
|
63
69
|
dtype: "fp32"
|
|
64
|
-
}),
|
|
70
|
+
}), _ = {
|
|
65
71
|
pooling: "mean",
|
|
66
72
|
normalize: !0
|
|
67
|
-
},
|
|
68
|
-
if (typeof
|
|
69
|
-
return
|
|
70
|
-
model:
|
|
71
|
-
dimensions:
|
|
73
|
+
}, v = await g(["probe"], _), y = v.dims?.at(-1);
|
|
74
|
+
if (typeof y != "number" || !Number.isInteger(y) || y <= 0) throw TypeError("Embedding model returned invalid dimensions");
|
|
75
|
+
return f(v, 1, y), {
|
|
76
|
+
model: e,
|
|
77
|
+
dimensions: y,
|
|
72
78
|
identity: {
|
|
73
79
|
package: "@huggingface/transformers",
|
|
74
80
|
version: "4.2.0",
|
|
75
|
-
model:
|
|
76
|
-
revision:
|
|
77
|
-
requestedRevision:
|
|
81
|
+
model: e,
|
|
82
|
+
revision: m,
|
|
83
|
+
requestedRevision: p,
|
|
78
84
|
dtype: "fp32",
|
|
79
85
|
device: "cpu",
|
|
80
86
|
pooling: "mean",
|
|
81
87
|
normalization: "l2",
|
|
82
|
-
dimensions:
|
|
88
|
+
dimensions: y
|
|
83
89
|
},
|
|
84
90
|
async embed(e) {
|
|
85
91
|
let t = [];
|
|
86
92
|
for (let n = 0; n < e.length; n += 32) {
|
|
87
93
|
let r = e.slice(n, n + 32);
|
|
88
|
-
t.push(...
|
|
94
|
+
t.push(...f(await g(r, _), r.length, y));
|
|
89
95
|
}
|
|
90
96
|
return t;
|
|
91
97
|
}
|
|
92
98
|
};
|
|
93
99
|
}
|
|
94
100
|
//#endregion
|
|
95
|
-
export {
|
|
101
|
+
export { p as createEmbeddingRuntime, c as resolveEmbeddingCacheDir };
|
|
96
102
|
|
|
97
103
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["export interface EmbeddingRuntimeRequest {\n\tmodel: string;\n\trevision?: string;\n}\n\nexport interface EmbeddingRuntimeIdentity {\n\treadonly package: \"@huggingface/transformers\";\n\treadonly version: string;\n\treadonly model: string;\n\treadonly revision: string;\n\treadonly requestedRevision?: string;\n\treadonly dtype: \"fp32\";\n\treadonly device: \"cpu\";\n\treadonly pooling: \"mean\";\n\treadonly normalization: \"l2\";\n\treadonly dimensions: number;\n}\n\nexport interface EmbeddingClient {\n\treadonly model: string;\n\treadonly dimensions: number;\n\treadonly identity: EmbeddingRuntimeIdentity;\n\tembed(texts: string[]): Promise<Float32Array[]>;\n}\n\nexport type EmbeddingRuntimeFactory = (\n\trequest: EmbeddingRuntimeRequest,\n) => Promise<EmbeddingClient | null>;\n\ninterface Tensor {\n\tdata: ArrayLike<number | bigint>;\n\tdims?: number[];\n}\n\ntype Extractor = (\n\ttexts: string[],\n\toptions: { pooling: \"mean\"; normalize: true },\n) => Promise<Tensor>;\n\nconst DEFAULT_MODEL = \"Xenova/bge-small-en-v1.5\";\nconst DEFAULT_REVISION = \"ea104dacec62c0de699686887e3f920caeb4f3e3\";\nconst CANONICAL_REVISION_PATTERN = /^[0-9a-f]{40}$/;\nlet allowRemoteModelsBeforeOffline: boolean | undefined;\n\nfunction isEmbeddingOffline(): boolean {\n\tconst value = process.env.CODEMEM_EMBEDDING_OFFLINE?.toLowerCase();\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\nfunction configureRemoteModelAccess(env: HubEnvironment): void {\n\tif (isEmbeddingOffline()) {\n\t\tallowRemoteModelsBeforeOffline ??= env.allowRemoteModels;\n\t\tenv.allowRemoteModels = false;\n\t\treturn;\n\t}\n\tif (allowRemoteModelsBeforeOffline === undefined) return;\n\tenv.allowRemoteModels = allowRemoteModelsBeforeOffline;\n\tallowRemoteModelsBeforeOffline = undefined;\n}\n\ninterface HubEnvironment {\n\tremoteHost: string;\n\tremotePathTemplate: string;\n\tallowRemoteModels: boolean;\n\tfetch(input: string | URL, init?: RequestInit): Promise<Response>;\n}\n\nfunction isLocalModelPath(model: string): boolean {\n\t// Transformers.js accepts at most owner/name as a Hub repository ID; other path forms are local.\n\treturn (\n\t\tmodel.startsWith(\".\") ||\n\t\tmodel.startsWith(\"/\") ||\n\t\tmodel.startsWith(\"~\") ||\n\t\tmodel.includes(\"\\\\\") ||\n\t\tmodel.split(\"/\").length > 2\n\t);\n}\n\nfunction configuredRevisionToResolve(\n\tmodel: string,\n\tconfiguredRevision: string | undefined,\n\tallowRemoteModels: boolean,\n): string | undefined {\n\tif (model === DEFAULT_MODEL && configuredRevision === DEFAULT_REVISION) return undefined;\n\tif (\n\t\tconfiguredRevision &&\n\t\tCANONICAL_REVISION_PATTERN.test(configuredRevision) &&\n\t\t(isLocalModelPath(model) || !allowRemoteModels)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn configuredRevision;\n}\n\nasync function resolveCanonicalRevision(\n\tmodel: string,\n\trevision: string,\n\tenv: HubEnvironment,\n): Promise<string> {\n\tconst remotePath = env.remotePathTemplate\n\t\t.replaceAll(\"{model}\", model.split(\"/\").map(encodeURIComponent).join(\"/\"))\n\t\t.replaceAll(\"{revision}\", encodeURIComponent(revision));\n\tconst url = `${env.remoteHost.replace(/\\/+$/, \"\")}/${remotePath.replace(/^\\/+|\\/+$/g, \"\")}/config.json`;\n\tconst headers = new Headers();\n\tconst hostname = new URL(url).hostname;\n\tif (hostname === \"huggingface.co\" || hostname === \"hf.co\") {\n\t\tconst token = process.env.HF_TOKEN ?? process.env.HF_ACCESS_TOKEN;\n\t\tif (token) headers.set(\"Authorization\", `Bearer ${token}`);\n\t}\n\tconst response = await env.fetch(url, {\n\t\tmethod: \"HEAD\",\n\t\tredirect: \"follow\",\n\t\theaders,\n\t\tsignal: AbortSignal.timeout(10_000),\n\t});\n\tif (!response.ok) {\n\t\tthrow new TypeError(\n\t\t\t`Unable to resolve Hugging Face model ${model}@${revision}: HTTP ${response.status}`,\n\t\t);\n\t}\n\tconst canonicalRevision = response.headers.get(\"x-repo-commit\")?.trim().toLowerCase();\n\tif (!canonicalRevision || !CANONICAL_REVISION_PATTERN.test(canonicalRevision)) {\n\t\tthrow new TypeError(\n\t\t\t`Hugging Face did not return a canonical commit for model ${model}@${revision}`,\n\t\t);\n\t}\n\treturn canonicalRevision;\n}\n\nfunction rows(output: Tensor, count: number, dimensions: number): Float32Array[] {\n\tif (\n\t\toutput.dims?.length !== 2 ||\n\t\t(output.dims?.length === 2 && (output.dims[0] !== count || output.dims[1] !== dimensions)) ||\n\t\toutput.data.length !== count * dimensions\n\t) {\n\t\tthrow new TypeError(\"Embedding model returned an invalid tensor shape or value count\");\n\t}\n\tconst result = Array.from({ length: count }, () => new Float32Array(dimensions));\n\tfor (let index = 0; index < output.data.length; index++) {\n\t\tconst value = output.data[index];\n\t\tconst number = typeof value === \"number\" ? Math.fround(value) : Number.NaN;\n\t\tif (!Number.isFinite(number)) {\n\t\t\tthrow new TypeError(`Embedding model returned non-finite data at index ${index}`);\n\t\t}\n\t\tconst row = result[Math.floor(index / dimensions)];\n\t\tif (!row) throw new TypeError(\"Embedding model returned an invalid tensor row\");\n\t\trow[index % dimensions] = number;\n\t}\n\treturn result;\n}\n\nexport async function createEmbeddingRuntime({\n\tmodel,\n\trevision: revisionRequest,\n}: EmbeddingRuntimeRequest): Promise<EmbeddingClient> {\n\tconst configuredRevision = revisionRequest?.trim();\n\tif (model !== DEFAULT_MODEL && !configuredRevision) {\n\t\tthrow new TypeError(\"A revision is required when creating a runtime for a custom model\");\n\t}\n\tconst { env, pipeline } = await import(\"@huggingface/transformers\");\n\tconfigureRemoteModelAccess(env);\n\tconst requestedRevision = configuredRevision || DEFAULT_REVISION;\n\tlet revision = requestedRevision;\n\tconst revisionToResolve = configuredRevisionToResolve(\n\t\tmodel,\n\t\tconfiguredRevision,\n\t\tenv.allowRemoteModels,\n\t);\n\tif (revisionToResolve) {\n\t\tif (isLocalModelPath(model)) {\n\t\t\tthrow new TypeError(\"Local embedding models require a 40-character revision identity\");\n\t\t} else if (!env.allowRemoteModels) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot resolve mutable embedding revision ${revisionToResolve} while remote models are disabled`,\n\t\t\t);\n\t\t} else {\n\t\t\trevision = await resolveCanonicalRevision(model, revisionToResolve, env);\n\t\t}\n\t}\n\t// Runtime validation below guards the structural boundary hidden by upstream's broad pipeline type.\n\tconst extractor = (await pipeline(\"feature-extraction\", model, {\n\t\trevision,\n\t\tdevice: \"cpu\",\n\t\tdtype: \"fp32\",\n\t})) as unknown as Extractor;\n\tconst options = { pooling: \"mean\", normalize: true } as const;\n\tconst probe = await extractor([\"probe\"], options);\n\tconst dimensions = probe.dims?.at(-1);\n\tif (typeof dimensions !== \"number\" || !Number.isInteger(dimensions) || dimensions <= 0) {\n\t\tthrow new TypeError(\"Embedding model returned invalid dimensions\");\n\t}\n\trows(probe, 1, dimensions);\n\n\treturn {\n\t\tmodel,\n\t\tdimensions,\n\t\tidentity: {\n\t\t\tpackage: \"@huggingface/transformers\",\n\t\t\tversion: \"4.2.0\",\n\t\t\tmodel,\n\t\t\trevision,\n\t\t\trequestedRevision,\n\t\t\tdtype: \"fp32\",\n\t\t\tdevice: \"cpu\",\n\t\t\tpooling: \"mean\",\n\t\t\tnormalization: \"l2\",\n\t\t\tdimensions,\n\t\t},\n\t\tasync embed(texts) {\n\t\t\tconst result: Float32Array[] = [];\n\t\t\tfor (let offset = 0; offset < texts.length; offset += 32) {\n\t\t\t\tconst batch = texts.slice(offset, offset + 32);\n\t\t\t\tresult.push(...rows(await extractor(batch, options), batch.length, dimensions));\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n"],"mappings":";AAuCA,IAAM,IAAgB,4BAChB,IAAmB,4CACnB,IAA6B,kBAC/B;AAEJ,SAAS,IAA8B;CACtC,IAAM,IAAQ,QAAQ,IAAI,2BAA2B,YAAY;CACjE,OAAO,MAAU,OAAO,MAAU,UAAU,MAAU;AACv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UACT,6CAA6C,EAAkB,kCAChE;CAIF;CAEA,IAAM,IAAa,MAAM,EAAS,sBAAsB,GAAO;EAC9D;EACA,QAAQ;EACR,OAAO;CACR,CAAC,GACK,IAAU;EAAE,SAAS;EAAQ,WAAW;CAAK,GAC7C,IAAQ,MAAM,EAAU,CAAC,OAAO,GAAG,CAAO,GAC1C,IAAa,EAAM,MAAM,GAAG,EAAE;CACpC,IAAI,OAAO,KAAe,YAAY,CAAC,OAAO,UAAU,CAAU,KAAK,KAAc,GACpF,MAAU,UAAU,6CAA6C;CAIlE,OAFA,EAAK,GAAO,GAAG,CAAU,GAElB;EACN;EACA;EACA,UAAU;GACT,SAAS;GACT,SAAS;GACT;GACA;GACA;GACA,OAAO;GACP,QAAQ;GACR,SAAS;GACT,eAAe;GACf;EACD;EACA,MAAM,MAAM,GAAO;GAClB,IAAM,IAAyB,CAAC;GAChC,KAAK,IAAI,IAAS,GAAG,IAAS,EAAM,QAAQ,KAAU,IAAI;IACzD,IAAM,IAAQ,EAAM,MAAM,GAAQ,IAAS,EAAE;IAC7C,EAAO,KAAK,GAAG,EAAK,MAAM,EAAU,GAAO,CAAO,GAAG,EAAM,QAAQ,CAAU,CAAC;GAC/E;GACA,OAAO;EACR;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport interface EmbeddingRuntimeRequest {\n\tmodel: string;\n\trevision?: string;\n}\n\nexport interface EmbeddingRuntimeIdentity {\n\treadonly package: \"@huggingface/transformers\";\n\treadonly version: string;\n\treadonly model: string;\n\treadonly revision: string;\n\treadonly requestedRevision?: string;\n\treadonly dtype: \"fp32\";\n\treadonly device: \"cpu\";\n\treadonly pooling: \"mean\";\n\treadonly normalization: \"l2\";\n\treadonly dimensions: number;\n}\n\nexport interface EmbeddingClient {\n\treadonly model: string;\n\treadonly dimensions: number;\n\treadonly identity: EmbeddingRuntimeIdentity;\n\tembed(texts: string[]): Promise<Float32Array[]>;\n}\n\nexport type EmbeddingRuntimeFactory = (\n\trequest: EmbeddingRuntimeRequest,\n) => Promise<EmbeddingClient | null>;\n\ninterface Tensor {\n\tdata: ArrayLike<number | bigint>;\n\tdims?: number[];\n}\n\ntype Extractor = (\n\ttexts: string[],\n\toptions: { pooling: \"mean\"; normalize: true },\n) => Promise<Tensor>;\n\nconst DEFAULT_MODEL = \"Xenova/bge-small-en-v1.5\";\nconst DEFAULT_REVISION = \"ea104dacec62c0de699686887e3f920caeb4f3e3\";\nconst CANONICAL_REVISION_PATTERN = /^[0-9a-f]{40}$/;\nlet allowRemoteModelsBeforeOffline: boolean | undefined;\n\nfunction isEmbeddingOffline(): boolean {\n\tconst value = process.env.CODEMEM_EMBEDDING_OFFLINE?.toLowerCase();\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\nfunction configureRemoteModelAccess(env: HubEnvironment): void {\n\tif (isEmbeddingOffline()) {\n\t\tallowRemoteModelsBeforeOffline ??= env.allowRemoteModels;\n\t\tenv.allowRemoteModels = false;\n\t\treturn;\n\t}\n\tif (allowRemoteModelsBeforeOffline === undefined) return;\n\tenv.allowRemoteModels = allowRemoteModelsBeforeOffline;\n\tallowRemoteModelsBeforeOffline = undefined;\n}\n\n/**\n * Directory for downloaded model files. Transformers.js defaults to a .cache\n * directory inside its own package, which a global npm install leaves owned by\n * root (unwritable for a non-root container user) and an upgrade replaces.\n */\nexport function resolveEmbeddingCacheDir(env: NodeJS.ProcessEnv = process.env): string {\n\tconst home = env.HOME?.trim() || homedir();\n\tconst configured = env.CODEMEM_EMBEDDING_CACHE_DIR?.trim();\n\tif (!configured) return join(home, \".codemem\", \"models\");\n\t// Quoted Docker or systemd values reach the process without shell expansion.\n\tif (configured === \"~\") return home;\n\tif (configured.startsWith(\"~/\")) return join(home, configured.slice(2));\n\treturn configured;\n}\n\ninterface HubEnvironment {\n\tcacheDir: string | null;\n\tremoteHost: string;\n\tremotePathTemplate: string;\n\tallowRemoteModels: boolean;\n\tfetch(input: string | URL, init?: RequestInit): Promise<Response>;\n}\n\nfunction isLocalModelPath(model: string): boolean {\n\t// Transformers.js accepts at most owner/name as a Hub repository ID; other path forms are local.\n\treturn (\n\t\tmodel.startsWith(\".\") ||\n\t\tmodel.startsWith(\"/\") ||\n\t\tmodel.startsWith(\"~\") ||\n\t\tmodel.includes(\"\\\\\") ||\n\t\tmodel.split(\"/\").length > 2\n\t);\n}\n\nfunction configuredRevisionToResolve(\n\tmodel: string,\n\tconfiguredRevision: string | undefined,\n\tallowRemoteModels: boolean,\n): string | undefined {\n\tif (model === DEFAULT_MODEL && configuredRevision === DEFAULT_REVISION) return undefined;\n\tif (\n\t\tconfiguredRevision &&\n\t\tCANONICAL_REVISION_PATTERN.test(configuredRevision) &&\n\t\t(isLocalModelPath(model) || !allowRemoteModels)\n\t) {\n\t\treturn undefined;\n\t}\n\treturn configuredRevision;\n}\n\nasync function resolveCanonicalRevision(\n\tmodel: string,\n\trevision: string,\n\tenv: HubEnvironment,\n): Promise<string> {\n\tconst remotePath = env.remotePathTemplate\n\t\t.replaceAll(\"{model}\", model.split(\"/\").map(encodeURIComponent).join(\"/\"))\n\t\t.replaceAll(\"{revision}\", encodeURIComponent(revision));\n\tconst url = `${env.remoteHost.replace(/\\/+$/, \"\")}/${remotePath.replace(/^\\/+|\\/+$/g, \"\")}/config.json`;\n\tconst headers = new Headers();\n\tconst hostname = new URL(url).hostname;\n\tif (hostname === \"huggingface.co\" || hostname === \"hf.co\") {\n\t\tconst token = process.env.HF_TOKEN ?? process.env.HF_ACCESS_TOKEN;\n\t\tif (token) headers.set(\"Authorization\", `Bearer ${token}`);\n\t}\n\tconst response = await env.fetch(url, {\n\t\tmethod: \"HEAD\",\n\t\tredirect: \"follow\",\n\t\theaders,\n\t\tsignal: AbortSignal.timeout(10_000),\n\t});\n\tif (!response.ok) {\n\t\tthrow new TypeError(\n\t\t\t`Unable to resolve Hugging Face model ${model}@${revision}: HTTP ${response.status}`,\n\t\t);\n\t}\n\tconst canonicalRevision = response.headers.get(\"x-repo-commit\")?.trim().toLowerCase();\n\tif (!canonicalRevision || !CANONICAL_REVISION_PATTERN.test(canonicalRevision)) {\n\t\tthrow new TypeError(\n\t\t\t`Hugging Face did not return a canonical commit for model ${model}@${revision}`,\n\t\t);\n\t}\n\treturn canonicalRevision;\n}\n\nfunction rows(output: Tensor, count: number, dimensions: number): Float32Array[] {\n\tif (\n\t\toutput.dims?.length !== 2 ||\n\t\t(output.dims?.length === 2 && (output.dims[0] !== count || output.dims[1] !== dimensions)) ||\n\t\toutput.data.length !== count * dimensions\n\t) {\n\t\tthrow new TypeError(\"Embedding model returned an invalid tensor shape or value count\");\n\t}\n\tconst result = Array.from({ length: count }, () => new Float32Array(dimensions));\n\tfor (let index = 0; index < output.data.length; index++) {\n\t\tconst value = output.data[index];\n\t\tconst number = typeof value === \"number\" ? Math.fround(value) : Number.NaN;\n\t\tif (!Number.isFinite(number)) {\n\t\t\tthrow new TypeError(`Embedding model returned non-finite data at index ${index}`);\n\t\t}\n\t\tconst row = result[Math.floor(index / dimensions)];\n\t\tif (!row) throw new TypeError(\"Embedding model returned an invalid tensor row\");\n\t\trow[index % dimensions] = number;\n\t}\n\treturn result;\n}\n\nexport async function createEmbeddingRuntime({\n\tmodel,\n\trevision: revisionRequest,\n}: EmbeddingRuntimeRequest): Promise<EmbeddingClient> {\n\tconst configuredRevision = revisionRequest?.trim();\n\tif (model !== DEFAULT_MODEL && !configuredRevision) {\n\t\tthrow new TypeError(\"A revision is required when creating a runtime for a custom model\");\n\t}\n\tconst { env, pipeline } = await import(\"@huggingface/transformers\");\n\tenv.cacheDir = resolveEmbeddingCacheDir();\n\tconfigureRemoteModelAccess(env);\n\tconst requestedRevision = configuredRevision || DEFAULT_REVISION;\n\tlet revision = requestedRevision;\n\tconst revisionToResolve = configuredRevisionToResolve(\n\t\tmodel,\n\t\tconfiguredRevision,\n\t\tenv.allowRemoteModels,\n\t);\n\tif (revisionToResolve) {\n\t\tif (isLocalModelPath(model)) {\n\t\t\tthrow new TypeError(\"Local embedding models require a 40-character revision identity\");\n\t\t} else if (!env.allowRemoteModels) {\n\t\t\tthrow new TypeError(\n\t\t\t\t`Cannot resolve mutable embedding revision ${revisionToResolve} while remote models are disabled`,\n\t\t\t);\n\t\t} else {\n\t\t\trevision = await resolveCanonicalRevision(model, revisionToResolve, env);\n\t\t}\n\t}\n\t// Runtime validation below guards the structural boundary hidden by upstream's broad pipeline type.\n\tconst extractor = (await pipeline(\"feature-extraction\", model, {\n\t\trevision,\n\t\tdevice: \"cpu\",\n\t\tdtype: \"fp32\",\n\t})) as unknown as Extractor;\n\tconst options = { pooling: \"mean\", normalize: true } as const;\n\tconst probe = await extractor([\"probe\"], options);\n\tconst dimensions = probe.dims?.at(-1);\n\tif (typeof dimensions !== \"number\" || !Number.isInteger(dimensions) || dimensions <= 0) {\n\t\tthrow new TypeError(\"Embedding model returned invalid dimensions\");\n\t}\n\trows(probe, 1, dimensions);\n\n\treturn {\n\t\tmodel,\n\t\tdimensions,\n\t\tidentity: {\n\t\t\tpackage: \"@huggingface/transformers\",\n\t\t\tversion: \"4.2.0\",\n\t\t\tmodel,\n\t\t\trevision,\n\t\t\trequestedRevision,\n\t\t\tdtype: \"fp32\",\n\t\t\tdevice: \"cpu\",\n\t\t\tpooling: \"mean\",\n\t\t\tnormalization: \"l2\",\n\t\t\tdimensions,\n\t\t},\n\t\tasync embed(texts) {\n\t\t\tconst result: Float32Array[] = [];\n\t\t\tfor (let offset = 0; offset < texts.length; offset += 32) {\n\t\t\t\tconst batch = texts.slice(offset, offset + 32);\n\t\t\t\tresult.push(...rows(await extractor(batch, options), batch.length, dimensions));\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t};\n}\n"],"mappings":";;;AA0CA,IAAM,IAAgB,4BAChB,IAAmB,4CACnB,IAA6B,kBAC/B;AAEJ,SAAS,IAA8B;CACtC,IAAM,IAAQ,QAAQ,IAAI,2BAA2B,Y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