@stll/anonymize-wasm 2.8.3 → 2.9.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/README.md CHANGED
@@ -18,14 +18,18 @@ and local document-provider tools remain Node-only. The binding is instantiated
18
18
  lazily on first use.
19
19
 
20
20
  ```ts
21
- import { loadDefaultPipeline } from "@stll/anonymize-wasm";
21
+ import { createPipeline } from "@stll/anonymize-wasm";
22
22
 
23
- // Loads the compressed default package bundled in the tarball.
24
- const pipeline = await loadDefaultPipeline();
23
+ const pipeline = await createPipeline({ language: "en" });
25
24
  const { redaction } = pipeline.redactText("A contract signed by Jan Novak.");
26
25
  console.log(redaction.redactedText);
27
26
  ```
28
27
 
28
+ `createPipeline()` accepts one supported language, an exact non-empty
29
+ combination such as `{ language: ["cs", "en"] }`, or `{ language: "all" }`.
30
+ Language-scoped pipelines are assembled and cached from lazy dictionary chunks;
31
+ `"all"` loads the bundled default prepared package.
32
+
29
33
  Bring your own prepared package (bytes, an `ArrayBuffer`, or a URL to fetch):
30
34
 
31
35
  ```ts
@@ -66,11 +70,16 @@ stllAnonymizeWasm({ packages: "none" });
66
70
  stllAnonymizeWasm({ packages: "all" });
67
71
  ```
68
72
 
69
- `"default"` selects the full-dictionary package that `loadDefaultPipeline()`
73
+ `"default"` selects the full-dictionary package that `createPipeline()` with
74
+ `language: "all"` or `loadDefaultPipeline()`
70
75
  (no argument) loads; a language code selects the scoped package that
71
76
  `loadDefaultPipeline("cs")` loads. Requesting a package that is not bundled
72
77
  fails the build.
73
78
 
79
+ The semantic factory supports `cs`, `de`, `en`, `es`, `fr`, `hu`, `it`, `lv`,
80
+ `pl`, `pt-br`, `ro`, `sk`, and `sv`. The lower-level artifact loader has
81
+ bundled scoped packages for `cs`, `de`, and `en` only.
82
+
74
83
  Interplay with the runtime loaders: the plugin only controls which assets ship,
75
84
  not which the code asks for. Calling `loadDefaultPipeline(language)` for a
76
85
  package you did not emit resolves to a missing asset URL and rejects with a
Binary file
package/dist/wasm.d.mts CHANGED
@@ -223,6 +223,7 @@ type NativeAddressSeedData = {
223
223
  boundary_words: string[];
224
224
  br_cep_cue_words: string[];
225
225
  unit_abbreviations: string[];
226
+ directional_abbreviations: string[];
226
227
  /** Present only when `standaloneStreetDetection` is enabled. */
227
228
  standalone_street?: NativeStandaloneStreetData;
228
229
  };
@@ -297,7 +298,9 @@ type NativeHotwordRuleData = {
297
298
  };
298
299
  type NativeSignatureData = {
299
300
  labels: string[];
301
+ person_value_labels: string[];
300
302
  person_list_labels: string[];
303
+ party_role_name_evidence: string;
301
304
  witness_phrases: string[];
302
305
  name_particles: string[];
303
306
  post_nominal_suffixes: string[];
@@ -1076,6 +1079,11 @@ type PreparedSearch = PreparedNativeAnonymizer;
1076
1079
  declare const PreparedAnonymizer: typeof PreparedNativeAnonymizer;
1077
1080
  type PreparedAnonymizer = PreparedNativeAnonymizer;
1078
1081
  //#endregion
1082
+ //#region src/pipeline-language.d.ts
1083
+ type SupportedLanguage = "cs" | "de" | "en" | "es" | "fr" | "hu" | "it" | "lv" | "pl" | "pt-br" | "ro" | "sk" | "sv";
1084
+ declare const SUPPORTED_LANGUAGES: readonly SupportedLanguage[];
1085
+ type PipelineLanguageSelection = SupportedLanguage | readonly [SupportedLanguage, ...SupportedLanguage[]] | "all";
1086
+ //#endregion
1079
1087
  //#region src/context.d.ts
1080
1088
  /**
1081
1089
  * Cached state for a single pipeline run (or a sequence of runs sharing the
@@ -1142,6 +1150,9 @@ type WasmBindingOptions = {
1142
1150
  * the underlying wasm module is instantiated a single time and cached. */
1143
1151
  declare const getBinding: () => Promise<NativeAnonymizeBinding>;
1144
1152
  type LoadPreparedPackageOptions = WasmBindingOptions;
1153
+ type CreatePipelineOptions = WasmBindingOptions & {
1154
+ language?: PipelineLanguageSelection;
1155
+ };
1145
1156
  /** Load a prepared package and return a pipeline ready to redact text. */
1146
1157
  declare const loadPipeline: (source: PreparedPackageSource, options?: LoadPreparedPackageOptions) => Promise<PreparedNativePipeline>;
1147
1158
  /** Load a prepared package and return the lower-level anonymizer. */
@@ -1165,6 +1176,8 @@ declare const loadDefaultPipeline: (language?: string, options?: LoadPreparedPac
1165
1176
  * folding the binding into the key would keep unbounded per-binding entries
1166
1177
  * alive. Injected-binding callers get a fresh pipeline each call. */
1167
1178
  declare const getDefaultPipeline: (language?: string, options?: LoadPreparedPackageOptions) => Promise<PreparedNativePipeline>;
1179
+ declare const createPipeline: ({ language, ...bindingOptions }?: CreatePipelineOptions) => Promise<PreparedNativePipeline>;
1180
+ declare const create_pipeline: typeof createPipeline;
1168
1181
  declare const redactDefaultText: (fullText: string, operators?: NativeOperatorConfig, language?: string) => Promise<NativeStaticRedactionResult>;
1169
1182
  declare const redactDefaultTextJson: (fullText: string, operators?: NativeOperatorConfig, language?: string) => Promise<string>;
1170
1183
  declare const native_package_version: (options?: WasmBindingOptions) => Promise<string>;
@@ -1184,5 +1197,5 @@ declare const summary_diagnostics_json: (config: NativeSearchPackageInput, fullT
1184
1197
  * fail-closed core used by Node and Python. This does not redact the PDF. */
1185
1198
  declare const inspect_pdf_json: (document: Uint8Array, observationsJson?: string, options?: WasmBindingOptions) => Promise<string>;
1186
1199
  //#endregion
1187
- export { type AnonymisationOperator, CALLER_DETECTION_CONTRACT_VERSION, CALLER_DETECTION_MAX_COUNT, CALLER_DETECTION_REQUEST_JSON_MAX_BYTES, CALLER_DETECTION_TEXT_MAX_BYTES, CAPABILITY_MANIFEST, CAPABILITY_MANIFEST_SCHEMA_VERSION, CAPABILITY_PARITY_PROFILES, CAPABILITY_RUNTIMES, CAPABILITY_SURFACES, type CapabilityManifest, type CapabilityParityProfile, type CapabilityRuntime, type CapabilitySurface, type CapabilitySurfaceId, ConvertExternalDetectionBatchOptions, DEFAULT_ENTITY_LABELS, DETECTION_SOURCES, DETECTOR_PRIORITY, type DefaultEntityLabel, type DetectionSource, type Dictionaries, ENTITY_CAPABILITIES, ENTITY_LABELS, ENTITY_SELECTIONS, EXTERNAL_DETECTION_BATCH_MAX_BYTES, EXTERNAL_DETECTION_BATCH_VERSION, EXTERNAL_DETECTION_DOCUMENT_MAX_BYTES, EXTERNAL_DETECTION_MAX_DETECTIONS, EXTERNAL_DETECTION_MAX_LABEL_MAPPINGS, EXTERNAL_DETECTION_MAX_METADATA_BYTES, EXTERNAL_DETECTION_OFFSET_UNITS, EXTERNAL_DETECTION_PROVIDER_ID_MAX_BYTES, type Entity, type EntityCapability, type EntityLabel, type EntitySelection, ExternalDetectionBatch, ExternalDetectionOffsetUnit, type GazetteerEntry, LoadPreparedPackageOptions, NATIVE_BINDING_PARITY_MEMBERS, NativeAnonymizeBinding, NativeAnonymizerFromConfigOptions, NativeAnonymizerFromPackageOptions, NativeBindingVersionOptions, NativeCallerDetection, NativeCallerRedactionOptions, NativeCreateSessionWithLifecycleOptions, NativeDiagnosticsBatchCallback, NativeNormalizeOptions, NativeOpenSessionArchiveOptions, NativeOperatorConfig, type NativePipelineBuildOptions, type NativePipelineCompatibility, NativePipelineEntity, NativePipelineFromPackageOptions, type NativePipelinePackageOptions, type NativePipelineUnsupportedFeature, NativePreparedRedactionSessionBinding, NativePreparedSearchBinding, type NativePreparedSearchConfig, NativePreparedSessionRedactionPlanBinding, NativeRedactionResult, NativeResultEventCallback, NativeSearchPackageInput, NativeSearchPackageOptions, NativeSessionBlockRedactionPlan, NativeSessionCallerRedactionInput, NativeSessionCallerRedactionPlanOptions, NativeSessionDeletionSummary, NativeSessionLifecycle, NativeSessionMetadata, NativeSessionRedactionAtOptions, NativeSessionStatus, NativeStaticRedactionResult, NativeTextReplacement, OPERATOR_TYPES, type OperatorConfig, type OperatorType, type PipelineConfig, type PipelineContext, PrepareSearchPackageOptions, PreparedAnonymizer, PreparedNativeAnonymizer, PreparedNativePipeline, PreparedNativeRedactionSession, PreparedNativeSessionRedactionPlan, PreparedPackageSource, PreparedSearch, type RedactionResult, type ReviewDecision, type ReviewedEntity, SESSION_CALLER_INPUTS_JSON_MAX_BYTES, SESSION_CALLER_MAX_INPUTS, SharedNativeDiagnosticsJsonOptions, SharedNativeDiagnosticsStreamJsonOptions, SharedNativePreparedPackageOptions, SharedNativeRedactTextJsonOptions, SharedNativeRedactTextOptions, SharedNativeRedactTextStreamJsonOptions, SharedNativeSearchPackageOptions, WasmBindingOptions, assertNativeBindingVersion, assertNativePipelineSupported, convert_external_detection_batch, createNativeAnonymizerFromConfig, createNativeAnonymizerFromPackage, createNativePipelineFromConfig, createNativePipelineFromPackage, createPipelineContext, deanonymise, defaultPackageUrl, diagnostics_json, diagnostics_stream_json, encodeNativeSearchConfig, encodeNativeSearchConfigInput, exportRedactionKey, getBinding, getDefaultPipeline, getNativeBindingVersion, getNativePipelineCompatibility, inspect_pdf_json, isNativeAnonymizeBinding, loadDefaultPipeline, loadPipeline, load_prepared_package, native_package_version, normalize_for_search, prepareNativePipelineConfig, prepareNativePipelinePackage, prepareNativeSearchPackage, prepare_search_package, redactDefaultText, redactDefaultTextJson, redact_text, redact_text_json, redact_text_stream_json, summary_diagnostics_json };
1200
+ export { type AnonymisationOperator, CALLER_DETECTION_CONTRACT_VERSION, CALLER_DETECTION_MAX_COUNT, CALLER_DETECTION_REQUEST_JSON_MAX_BYTES, CALLER_DETECTION_TEXT_MAX_BYTES, CAPABILITY_MANIFEST, CAPABILITY_MANIFEST_SCHEMA_VERSION, CAPABILITY_PARITY_PROFILES, CAPABILITY_RUNTIMES, CAPABILITY_SURFACES, type CapabilityManifest, type CapabilityParityProfile, type CapabilityRuntime, type CapabilitySurface, type CapabilitySurfaceId, ConvertExternalDetectionBatchOptions, CreatePipelineOptions, DEFAULT_ENTITY_LABELS, DETECTION_SOURCES, DETECTOR_PRIORITY, type DefaultEntityLabel, type DetectionSource, type Dictionaries, ENTITY_CAPABILITIES, ENTITY_LABELS, ENTITY_SELECTIONS, EXTERNAL_DETECTION_BATCH_MAX_BYTES, EXTERNAL_DETECTION_BATCH_VERSION, EXTERNAL_DETECTION_DOCUMENT_MAX_BYTES, EXTERNAL_DETECTION_MAX_DETECTIONS, EXTERNAL_DETECTION_MAX_LABEL_MAPPINGS, EXTERNAL_DETECTION_MAX_METADATA_BYTES, EXTERNAL_DETECTION_OFFSET_UNITS, EXTERNAL_DETECTION_PROVIDER_ID_MAX_BYTES, type Entity, type EntityCapability, type EntityLabel, type EntitySelection, ExternalDetectionBatch, ExternalDetectionOffsetUnit, type GazetteerEntry, LoadPreparedPackageOptions, NATIVE_BINDING_PARITY_MEMBERS, NativeAnonymizeBinding, NativeAnonymizerFromConfigOptions, NativeAnonymizerFromPackageOptions, NativeBindingVersionOptions, NativeCallerDetection, NativeCallerRedactionOptions, NativeCreateSessionWithLifecycleOptions, NativeDiagnosticsBatchCallback, NativeNormalizeOptions, NativeOpenSessionArchiveOptions, NativeOperatorConfig, type NativePipelineBuildOptions, type NativePipelineCompatibility, NativePipelineEntity, NativePipelineFromPackageOptions, type NativePipelinePackageOptions, type NativePipelineUnsupportedFeature, NativePreparedRedactionSessionBinding, NativePreparedSearchBinding, type NativePreparedSearchConfig, NativePreparedSessionRedactionPlanBinding, NativeRedactionResult, NativeResultEventCallback, NativeSearchPackageInput, NativeSearchPackageOptions, NativeSessionBlockRedactionPlan, NativeSessionCallerRedactionInput, NativeSessionCallerRedactionPlanOptions, NativeSessionDeletionSummary, NativeSessionLifecycle, NativeSessionMetadata, NativeSessionRedactionAtOptions, NativeSessionStatus, NativeStaticRedactionResult, NativeTextReplacement, OPERATOR_TYPES, type OperatorConfig, type OperatorType, type PipelineConfig, type PipelineContext, type PipelineLanguageSelection, PrepareSearchPackageOptions, PreparedAnonymizer, PreparedNativeAnonymizer, PreparedNativePipeline, PreparedNativeRedactionSession, PreparedNativeSessionRedactionPlan, PreparedPackageSource, PreparedSearch, type RedactionResult, type ReviewDecision, type ReviewedEntity, SESSION_CALLER_INPUTS_JSON_MAX_BYTES, SESSION_CALLER_MAX_INPUTS, SUPPORTED_LANGUAGES, SharedNativeDiagnosticsJsonOptions, SharedNativeDiagnosticsStreamJsonOptions, SharedNativePreparedPackageOptions, SharedNativeRedactTextJsonOptions, SharedNativeRedactTextOptions, SharedNativeRedactTextStreamJsonOptions, SharedNativeSearchPackageOptions, type SupportedLanguage, WasmBindingOptions, assertNativeBindingVersion, assertNativePipelineSupported, convert_external_detection_batch, createNativeAnonymizerFromConfig, createNativeAnonymizerFromPackage, createNativePipelineFromConfig, createNativePipelineFromPackage, createPipeline, createPipelineContext, create_pipeline, deanonymise, defaultPackageUrl, diagnostics_json, diagnostics_stream_json, encodeNativeSearchConfig, encodeNativeSearchConfigInput, exportRedactionKey, getBinding, getDefaultPipeline, getNativeBindingVersion, getNativePipelineCompatibility, inspect_pdf_json, isNativeAnonymizeBinding, loadDefaultPipeline, loadPipeline, load_prepared_package, native_package_version, normalize_for_search, prepareNativePipelineConfig, prepareNativePipelinePackage, prepareNativeSearchPackage, prepare_search_package, redactDefaultText, redactDefaultTextJson, redact_text, redact_text_json, redact_text_stream_json, summary_diagnostics_json };
1188
1201
  //# sourceMappingURL=wasm.d.mts.map
package/dist/wasm.mjs CHANGED
@@ -70,13 +70,13 @@ const isNativeAnonymizeBinding = (candidate) => {
70
70
  };
71
71
  const CALLER_DETECTION_CONTRACT_VERSION = 2;
72
72
  const CALLER_DETECTION_MAX_COUNT = 1e6;
73
- const CALLER_DETECTION_TEXT_MAX_BYTES = 64 * 1024 * 1024;
74
- const CALLER_DETECTION_REQUEST_JSON_MAX_BYTES = 16 * 1024 * 1024;
73
+ const CALLER_DETECTION_TEXT_MAX_BYTES = 67108864;
74
+ const CALLER_DETECTION_REQUEST_JSON_MAX_BYTES = 16777216;
75
75
  const SESSION_CALLER_MAX_INPUTS = 1e5;
76
- const SESSION_CALLER_INPUTS_JSON_MAX_BYTES = 64 * 1024 * 1024;
76
+ const SESSION_CALLER_INPUTS_JSON_MAX_BYTES = 67108864;
77
77
  const EXTERNAL_DETECTION_BATCH_VERSION = 1;
78
- const EXTERNAL_DETECTION_BATCH_MAX_BYTES = 16 * 1024 * 1024;
79
- const EXTERNAL_DETECTION_DOCUMENT_MAX_BYTES = 64 * 1024 * 1024;
78
+ const EXTERNAL_DETECTION_BATCH_MAX_BYTES = 16777216;
79
+ const EXTERNAL_DETECTION_DOCUMENT_MAX_BYTES = 67108864;
80
80
  const EXTERNAL_DETECTION_MAX_DETECTIONS = 1e5;
81
81
  const EXTERNAL_DETECTION_MAX_LABEL_MAPPINGS = 4096;
82
82
  const EXTERNAL_DETECTION_MAX_METADATA_BYTES = 256;
@@ -838,50 +838,62 @@ const assertPdfPixelPages = (pagePixels) => {
838
838
  for (const [index, page] of pagePixels.entries()) if (!(page instanceof Uint8Array)) throw new TypeError(`PDF pagePixels[${index}] must be a Uint8Array`);
839
839
  };
840
840
  //#endregion
841
- //#region src/context.ts
842
- /** Create a fresh, empty pipeline context. */
843
- const createPipelineContext = () => ({
844
- nativePipelinePackage: null,
845
- nativePipelinePackageKey: "",
846
- nativePipelinePackagePromise: null
847
- });
848
- /**
849
- * Module-level default context. Used when callers
850
- * don't provide an explicit context, preserving full
851
- * backward compatibility with the existing API.
852
- */
853
- const defaultContext = createPipelineContext();
854
- //#endregion
855
- //#region src/redact.ts
856
- /**
857
- * Serialize the redaction key to JSON for export.
858
- * Includes operator metadata so the export is self-describing.
859
- */
860
- const exportRedactionKey = (redactionMap, operatorMap) => {
861
- const entries = {};
862
- for (const [placeholder, value] of redactionMap) entries[placeholder] = {
863
- original: value,
864
- operator: operatorMap.get(placeholder) ?? "replace"
865
- };
866
- return JSON.stringify({ entries }, null, 2);
867
- };
868
- /**
869
- * De-anonymise text using a redaction key.
870
- * Replaces placeholders back with original values.
871
- * Only works for reversible operators (replace).
872
- */
873
- const deanonymise = (redactedText, redactionMap) => {
874
- let result = redactedText;
875
- for (const [placeholder, original] of redactionMap) result = result.replaceAll(placeholder, original);
876
- return result;
877
- };
878
- //#endregion
879
- //#region src/types.ts
880
- const isLegalFormsEnabled = (config) => config.enableLegalForms !== false;
881
- //#endregion
882
- //#region src/language-scope.ts
883
- const scopeData = {
884
- _comment: "Default dictionary scopes for content language hints. Lower-level caller config can still override name corpus languages and deny-list countries independently.",
841
+ //#region src/data/language-scopes.json
842
+ var language_scopes_default = {
843
+ _comment: "Default dictionary scopes for content language hints. The all-language city scope preserves the data package defaults and covers every supported language. Lower-level caller config can still override name corpus languages and deny-list countries independently.",
844
+ allLanguageCityCountries: [
845
+ "AR",
846
+ "AT",
847
+ "AU",
848
+ "BE",
849
+ "BG",
850
+ "BO",
851
+ "BR",
852
+ "CA",
853
+ "CH",
854
+ "CL",
855
+ "CO",
856
+ "CR",
857
+ "CU",
858
+ "CZ",
859
+ "DE",
860
+ "DK",
861
+ "DO",
862
+ "EC",
863
+ "ES",
864
+ "FI",
865
+ "FR",
866
+ "GB",
867
+ "GR",
868
+ "GT",
869
+ "HN",
870
+ "HR",
871
+ "HU",
872
+ "IE",
873
+ "IT",
874
+ "LU",
875
+ "LV",
876
+ "MC",
877
+ "MD",
878
+ "MX",
879
+ "NI",
880
+ "NL",
881
+ "NO",
882
+ "NZ",
883
+ "PA",
884
+ "PE",
885
+ "PL",
886
+ "PT",
887
+ "PY",
888
+ "RO",
889
+ "SE",
890
+ "SI",
891
+ "SK",
892
+ "SV",
893
+ "US",
894
+ "UY",
895
+ "VE"
896
+ ],
885
897
  languages: {
886
898
  "cs": {
887
899
  "nameCorpusLanguages": ["cs", "sk"],
@@ -974,7 +986,10 @@ const scopeData = {
974
986
  }
975
987
  }
976
988
  };
977
- const normalizeLanguage$1 = (language) => language.trim().toLowerCase();
989
+ //#endregion
990
+ //#region src/language-scope.ts
991
+ const scopeData = language_scopes_default;
992
+ const normalizeLanguage$2 = (language) => language.trim().toLowerCase();
978
993
  const fallbackLanguage = (language) => {
979
994
  const index = language.indexOf("-");
980
995
  return index === -1 ? null : language.slice(0, index);
@@ -988,7 +1003,7 @@ const uniquePush = (target, values) => {
988
1003
  }
989
1004
  };
990
1005
  const resolveLanguageScope = (language) => {
991
- const normalized = normalizeLanguage$1(language);
1006
+ const normalized = normalizeLanguage$2(language);
992
1007
  if (normalized.length === 0) return null;
993
1008
  const exact = scopeData.languages[normalized];
994
1009
  if (exact !== void 0) return exact;
@@ -1004,21 +1019,50 @@ const applyPipelineLanguageScope = (config) => {
1004
1019
  if (languages.length === 0) return config;
1005
1020
  const nameCorpusLanguages = [];
1006
1021
  const denyListCountries = [];
1022
+ let hasResolvedScope = false;
1007
1023
  for (const language of languages) {
1008
1024
  const scope = resolveLanguageScope(language);
1009
1025
  if (scope === null) continue;
1026
+ hasResolvedScope = true;
1010
1027
  uniquePush(nameCorpusLanguages, scope.nameCorpusLanguages ?? []);
1011
1028
  uniquePush(denyListCountries, scope.denyListCountries ?? []);
1012
1029
  }
1013
1030
  const next = {};
1014
- if (config.nameCorpusLanguages === void 0 && nameCorpusLanguages.length > 0) next.nameCorpusLanguages = nameCorpusLanguages;
1015
- if (config.denyListCountries === void 0 && denyListCountries.length > 0) next.denyListCountries = denyListCountries;
1031
+ if (config.nameCorpusLanguages === void 0 && hasResolvedScope) next.nameCorpusLanguages = nameCorpusLanguages;
1032
+ if (config.denyListCountries === void 0 && hasResolvedScope) next.denyListCountries = denyListCountries;
1016
1033
  return Object.keys(next).length === 0 ? config : {
1017
1034
  ...config,
1018
1035
  ...next
1019
1036
  };
1020
1037
  };
1021
1038
  //#endregion
1039
+ //#region src/build-native-package.ts
1040
+ const EMPTY_NAME_CORPUS_SCOPE = ["und"];
1041
+ const defaultDictionaryBundleOptions = (config) => ({
1042
+ ...config.denyListCountries === void 0 ? { cityCountries: language_scopes_default.allLanguageCityCountries } : {
1043
+ countries: config.denyListCountries,
1044
+ cityCountries: config.denyListCountries
1045
+ },
1046
+ ...config.nameCorpusLanguages === void 0 ? {} : { nameLanguages: config.nameCorpusLanguages.length === 0 ? EMPTY_NAME_CORPUS_SCOPE : config.nameCorpusLanguages }
1047
+ });
1048
+ //#endregion
1049
+ //#region src/context.ts
1050
+ /** Create a fresh, empty pipeline context. */
1051
+ const createPipelineContext = () => ({
1052
+ nativePipelinePackage: null,
1053
+ nativePipelinePackageKey: "",
1054
+ nativePipelinePackagePromise: null
1055
+ });
1056
+ /**
1057
+ * Module-level default context. Used when callers
1058
+ * don't provide an explicit context, preserving full
1059
+ * backward compatibility with the existing API.
1060
+ */
1061
+ const defaultContext = createPipelineContext();
1062
+ //#endregion
1063
+ //#region src/types.ts
1064
+ const isLegalFormsEnabled = (config) => config.enableLegalForms !== false;
1065
+ //#endregion
1022
1066
  //#region src/util/language-selection.ts
1023
1067
  const normalizeLanguageCode = (language) => language.trim().toLowerCase();
1024
1068
  const normalizeLanguageSelection = (languages) => languages === void 0 ? [] : languages.map(normalizeLanguageCode).filter((language) => language.length > 0);
@@ -1030,7 +1074,8 @@ const languageSelectionKey = (languages) => {
1030
1074
  //#region src/pipeline-cache-key.ts
1031
1075
  const DEFAULT_CUSTOM_REGEX_SCORE = .9;
1032
1076
  const contentLanguageFingerprint = (config) => {
1033
- return languageSelectionKey(config.languages ?? (config.language === void 0 ? [] : [config.language]));
1077
+ const languages = config.languages ?? (config.language === void 0 ? [] : [config.language]);
1078
+ return languageSelectionKey(languages);
1034
1079
  };
1035
1080
  const pipelineConfigKey = (config, gazetteerEntries) => {
1036
1081
  const legalFormsEnabled = isLegalFormsEnabled(config);
@@ -1140,14 +1185,15 @@ const prepareNativePipelinePackage = async ({ binding, config, gazetteerEntries
1140
1185
  return new Uint8Array(packageBytes);
1141
1186
  };
1142
1187
  const createNativePipelineFromConfig = async ({ binding, config, gazetteerEntries = [], context }) => {
1188
+ const packageBytes = await getCachedNativePipelinePackage({
1189
+ binding,
1190
+ config,
1191
+ gazetteerEntries,
1192
+ ...context ? { context } : {}
1193
+ });
1143
1194
  return createNativePipelineFromPackage({
1144
1195
  binding,
1145
- packageBytes: await getCachedNativePipelinePackage({
1146
- binding,
1147
- config,
1148
- gazetteerEntries,
1149
- ...context ? { context } : {}
1150
- })
1196
+ packageBytes
1151
1197
  });
1152
1198
  };
1153
1199
  const getCachedNativePipelinePackage = async ({ binding, config, gazetteerEntries = [], context, compressed = false }) => {
@@ -1208,6 +1254,141 @@ const nativePackageCacheKey = ({ binding, config, gazetteerEntries, compressed }
1208
1254
  pipelineConfigKey(config, gazetteerEntries)
1209
1255
  ].join(":");
1210
1256
  //#endregion
1257
+ //#region src/native-default-config.ts
1258
+ const DEFAULT_NATIVE_PIPELINE_CONFIG = {
1259
+ threshold: .3,
1260
+ enableTriggerPhrases: true,
1261
+ enableRegex: true,
1262
+ enableLegalForms: true,
1263
+ enableNameCorpus: true,
1264
+ enableDenyList: true,
1265
+ enableGazetteer: false,
1266
+ enableCountries: true,
1267
+ enableConfidenceBoost: true,
1268
+ enableCoreference: true,
1269
+ enableHotwordRules: true,
1270
+ enableZoneClassification: true,
1271
+ standaloneStreetDetection: "off",
1272
+ labels: [...DEFAULT_ENTITY_LABELS],
1273
+ workspaceId: "native-pipeline-default"
1274
+ };
1275
+ //#endregion
1276
+ //#region src/pipeline-language.ts
1277
+ const isSupportedLanguage = (language) => Object.hasOwn(language_scopes_default.languages, language);
1278
+ const SUPPORTED_LANGUAGES = Object.freeze(Object.keys(language_scopes_default.languages).filter(isSupportedLanguage).toSorted());
1279
+ const normalizeLanguage$1 = (language) => {
1280
+ if (typeof language !== "string") throw new TypeError("Pipeline language codes must be strings");
1281
+ const normalized = language.trim().toLowerCase();
1282
+ if (!isSupportedLanguage(normalized)) throw new RangeError(`Unsupported pipeline language ${JSON.stringify(language)}; expected one of: ${SUPPORTED_LANGUAGES.join(", ")}`);
1283
+ return normalized;
1284
+ };
1285
+ const normalizePipelineLanguageSelection = (selection) => {
1286
+ if (selection === void 0 || typeof selection === "string" && selection.trim().toLowerCase() === "all") return { type: "all" };
1287
+ const requested = Array.isArray(selection) ? selection : [selection];
1288
+ if (requested.length === 0) throw new RangeError("Pipeline language selection must not be empty");
1289
+ const normalized = [...new Set(requested.map(normalizeLanguage$1))].toSorted();
1290
+ const first = normalized.at(0);
1291
+ if (first === void 0) throw new RangeError("Pipeline language selection must not be empty");
1292
+ return {
1293
+ type: "languages",
1294
+ languages: [first, ...normalized.slice(1)]
1295
+ };
1296
+ };
1297
+ const pipelineLanguageSelectionKey = (selection) => selection.type === "all" ? "all" : selection.languages.join(",");
1298
+ //#endregion
1299
+ //#region src/create-pipeline.ts
1300
+ const dictionaryCache = /* @__PURE__ */ new Map();
1301
+ const semanticPipelineCache = /* @__PURE__ */ new WeakMap();
1302
+ const MAX_SEMANTIC_PIPELINE_CACHE_ENTRIES = 8;
1303
+ const getCachedEntry = (cache, key) => {
1304
+ const cached = cache.get(key);
1305
+ if (cached === void 0) return;
1306
+ cache.delete(key);
1307
+ cache.set(key, cached);
1308
+ return cached;
1309
+ };
1310
+ const setCachedEntry = (cache, key, value) => {
1311
+ cache.set(key, value);
1312
+ if (cache.size <= MAX_SEMANTIC_PIPELINE_CACHE_ENTRIES) return;
1313
+ const oldestKey = cache.keys().next().value;
1314
+ if (oldestKey !== void 0) cache.delete(oldestKey);
1315
+ };
1316
+ const loadSemanticDictionaries = (key, config) => {
1317
+ const cached = getCachedEntry(dictionaryCache, key);
1318
+ if (cached !== void 0) return cached;
1319
+ let dictionaries;
1320
+ dictionaries = import("@stll/anonymize-data/cities").then(({ loadDictionaryBundle }) => loadDictionaryBundle(defaultDictionaryBundleOptions(config))).catch((error) => {
1321
+ if (dictionaryCache.get(key) === dictionaries) dictionaryCache.delete(key);
1322
+ throw error;
1323
+ });
1324
+ setCachedEntry(dictionaryCache, key, dictionaries);
1325
+ return dictionaries;
1326
+ };
1327
+ const pipelineConfigFor = (selection) => {
1328
+ if (selection.type === "all") return {
1329
+ ...DEFAULT_NATIVE_PIPELINE_CONFIG,
1330
+ labels: [...DEFAULT_NATIVE_PIPELINE_CONFIG.labels]
1331
+ };
1332
+ const [language, ...languages] = selection.languages;
1333
+ return applyPipelineLanguageScope({
1334
+ ...DEFAULT_NATIVE_PIPELINE_CONFIG,
1335
+ labels: [...DEFAULT_NATIVE_PIPELINE_CONFIG.labels],
1336
+ workspaceId: `default-pipeline:${pipelineLanguageSelectionKey(selection)}`,
1337
+ ...languages.length === 0 ? { language } : { languages: [language, ...languages] }
1338
+ });
1339
+ };
1340
+ const semanticPipelineCacheFor = (binding) => {
1341
+ const cached = semanticPipelineCache.get(binding);
1342
+ if (cached !== void 0) return cached;
1343
+ const created = /* @__PURE__ */ new Map();
1344
+ semanticPipelineCache.set(binding, created);
1345
+ return created;
1346
+ };
1347
+ const createSemanticPipeline = ({ binding, selection }) => {
1348
+ const key = pipelineLanguageSelectionKey(selection);
1349
+ const cache = semanticPipelineCacheFor(binding);
1350
+ const cached = getCachedEntry(cache, key);
1351
+ if (cached !== void 0) return cached;
1352
+ const config = pipelineConfigFor(selection);
1353
+ let pipeline;
1354
+ pipeline = loadSemanticDictionaries(key, config).then((dictionaries) => createNativePipelineFromConfig({
1355
+ binding,
1356
+ config: {
1357
+ ...config,
1358
+ dictionaries
1359
+ }
1360
+ })).catch((error) => {
1361
+ if (cache.get(key) === pipeline) cache.delete(key);
1362
+ throw error;
1363
+ });
1364
+ setCachedEntry(cache, key, pipeline);
1365
+ return pipeline;
1366
+ };
1367
+ //#endregion
1368
+ //#region src/redact.ts
1369
+ /**
1370
+ * Serialize the redaction key to JSON for export.
1371
+ * Includes operator metadata so the export is self-describing.
1372
+ */
1373
+ const exportRedactionKey = (redactionMap, operatorMap) => {
1374
+ const entries = {};
1375
+ for (const [placeholder, value] of redactionMap) entries[placeholder] = {
1376
+ original: value,
1377
+ operator: operatorMap.get(placeholder) ?? "replace"
1378
+ };
1379
+ return JSON.stringify({ entries }, null, 2);
1380
+ };
1381
+ /**
1382
+ * De-anonymise text using a redaction key.
1383
+ * Replaces placeholders back with original values.
1384
+ * Only works for reversible operators (replace).
1385
+ */
1386
+ const deanonymise = (redactedText, redactionMap) => {
1387
+ let result = redactedText;
1388
+ for (const [placeholder, original] of redactionMap) result = result.replaceAll(placeholder, original);
1389
+ return result;
1390
+ };
1391
+ //#endregion
1211
1392
  //#region src/wasm.ts
1212
1393
  const GLUE_MODULE = "index.js";
1213
1394
  const WASM_MODULE = "index_bg.wasm";
@@ -1216,10 +1397,18 @@ const NATIVE_ASSET_DIR = "native";
1216
1397
  const ASSET_DIR_ENV = "STLL_ANONYMIZE_ASSET_DIR";
1217
1398
  const DEFAULT_PACKAGE_FILE = "native-pipeline.stlanonpkg";
1218
1399
  const LANGUAGE_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
1400
+ const HTML_MEDIA_TYPES = /* @__PURE__ */ new Set(["application/xhtml+xml", "text/html"]);
1219
1401
  const DEFAULT_PIPELINE_CACHE_KEY = "<default>";
1220
1402
  const DEFAULT_PIPELINE_CACHE_MAX_ENTRIES = 32;
1221
1403
  let bindingPromise;
1222
1404
  const defaultPipelineCache = /* @__PURE__ */ new Map();
1405
+ const unavailablePackageUrls = /* @__PURE__ */ new Set();
1406
+ var PreparedPackageUnavailableError = class extends Error {
1407
+ constructor(href, options) {
1408
+ super(`Prepared package is unavailable: ${href}`, options);
1409
+ this.name = "PreparedPackageUnavailableError";
1410
+ }
1411
+ };
1223
1412
  /** Instantiate (once) and return the wasm binding. Safe to call repeatedly:
1224
1413
  * the underlying wasm module is instantiated a single time and cached. */
1225
1414
  const getBinding = () => {
@@ -1272,11 +1461,27 @@ const toPackageBytes = async (source) => {
1272
1461
  if (source instanceof Uint8Array) return source;
1273
1462
  if (source instanceof ArrayBuffer) return new Uint8Array(source);
1274
1463
  const href = source instanceof URL ? source.href : source;
1275
- if (href.startsWith("file:")) return readFileUrlBytes(href);
1464
+ if (href.startsWith("file:")) try {
1465
+ return await readFileUrlBytes(href);
1466
+ } catch (error) {
1467
+ if (isMissingFileError(error)) throw new PreparedPackageUnavailableError(href, { cause: error });
1468
+ throw error;
1469
+ }
1276
1470
  const response = await fetch(href);
1277
- if (!response.ok) throw new Error(`Failed to fetch prepared package (${response.status} ${response.statusText})`);
1471
+ if (!response.ok) {
1472
+ if (response.status === 404) throw new PreparedPackageUnavailableError(href);
1473
+ throw new Error(`Failed to fetch prepared package (${response.status} ${response.statusText})`);
1474
+ }
1475
+ if (isHtmlResponse(response)) throw new PreparedPackageUnavailableError(href);
1278
1476
  return new Uint8Array(await response.arrayBuffer());
1279
1477
  };
1478
+ const isHtmlResponse = (response) => {
1479
+ const contentType = response.headers.get("content-type");
1480
+ if (contentType === null) return false;
1481
+ const mediaType = contentType.split(";", 1).at(0)?.trim().toLowerCase();
1482
+ return mediaType !== void 0 && HTML_MEDIA_TYPES.has(mediaType);
1483
+ };
1484
+ const isMissingFileError = (error) => typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1280
1485
  /** Read a `file:` URL through node:fs. The import is dynamic and gated behind
1281
1486
  * the `file:` check (never reached in browsers); the specifier is a runtime
1282
1487
  * value so the bundler leaves it alone, mirroring the runtime glue import in
@@ -1317,6 +1522,7 @@ const loadDefaultPipeline = async (language, options) => {
1317
1522
  try {
1318
1523
  return await loadPipeline(defaultPackageUrl(language), options);
1319
1524
  } catch (error) {
1525
+ if (!(error instanceof PreparedPackageUnavailableError)) throw error;
1320
1526
  const normalized = language === void 0 ? void 0 : normalizeLanguage(language);
1321
1527
  const baseLanguage = normalized?.split("-").at(0);
1322
1528
  if (baseLanguage === void 0 || baseLanguage === normalized) throw error;
@@ -1371,6 +1577,37 @@ const getDefaultPipeline = (language, options) => {
1371
1577
  touchDefaultPipelineCacheEntry(key, pipeline);
1372
1578
  return pipeline;
1373
1579
  };
1580
+ const createPipeline = async ({ language, ...bindingOptions } = {}) => {
1581
+ const selection = normalizePipelineLanguageSelection(language);
1582
+ if (selection.type === "all") {
1583
+ const packageUrl = defaultPackageUrl();
1584
+ if (!unavailablePackageUrls.has(packageUrl.href)) try {
1585
+ return await getDefaultPipeline(void 0, bindingOptions);
1586
+ } catch (error) {
1587
+ if (!(error instanceof PreparedPackageUnavailableError)) throw error;
1588
+ unavailablePackageUrls.add(packageUrl.href);
1589
+ }
1590
+ return createSemanticPipeline({
1591
+ binding: await resolveBinding(bindingOptions),
1592
+ selection
1593
+ });
1594
+ }
1595
+ const [singleLanguage, ...additionalLanguages] = selection.languages;
1596
+ if (additionalLanguages.length === 0) {
1597
+ const packageUrl = defaultPackageUrl(singleLanguage);
1598
+ if (!unavailablePackageUrls.has(packageUrl.href)) try {
1599
+ return await getDefaultPipeline(singleLanguage, bindingOptions);
1600
+ } catch (error) {
1601
+ if (!(error instanceof PreparedPackageUnavailableError)) throw error;
1602
+ unavailablePackageUrls.add(packageUrl.href);
1603
+ }
1604
+ }
1605
+ return createSemanticPipeline({
1606
+ binding: await resolveBinding(bindingOptions),
1607
+ selection
1608
+ });
1609
+ };
1610
+ const create_pipeline = createPipeline;
1374
1611
  const redactDefaultText = async (fullText, operators, language) => (await getDefaultPipeline(language)).redactText(fullText, operators);
1375
1612
  const redactDefaultTextJson = async (fullText, operators, language) => (await getDefaultPipeline(language)).redact_text_json(fullText, operators);
1376
1613
  const native_package_version = async (options) => native_package_version$1(await resolveBinding(options));
@@ -1445,6 +1682,6 @@ const normalizeLanguage = (language) => {
1445
1682
  return normalized;
1446
1683
  };
1447
1684
  //#endregion
1448
- export { CALLER_DETECTION_CONTRACT_VERSION, CALLER_DETECTION_MAX_COUNT, CALLER_DETECTION_REQUEST_JSON_MAX_BYTES, CALLER_DETECTION_TEXT_MAX_BYTES, CAPABILITY_MANIFEST, CAPABILITY_MANIFEST_SCHEMA_VERSION, CAPABILITY_PARITY_PROFILES, CAPABILITY_RUNTIMES, CAPABILITY_SURFACES, DEFAULT_ENTITY_LABELS, DETECTION_SOURCES, DETECTOR_PRIORITY, ENTITY_CAPABILITIES, ENTITY_LABELS, ENTITY_SELECTIONS, EXTERNAL_DETECTION_BATCH_MAX_BYTES, EXTERNAL_DETECTION_BATCH_VERSION, EXTERNAL_DETECTION_DOCUMENT_MAX_BYTES, EXTERNAL_DETECTION_MAX_DETECTIONS, EXTERNAL_DETECTION_MAX_LABEL_MAPPINGS, EXTERNAL_DETECTION_MAX_METADATA_BYTES, EXTERNAL_DETECTION_OFFSET_UNITS, EXTERNAL_DETECTION_PROVIDER_ID_MAX_BYTES, NATIVE_BINDING_PARITY_MEMBERS, OPERATOR_TYPES, PreparedAnonymizer, PreparedNativeAnonymizer, PreparedNativePipeline, PreparedNativeRedactionSession, PreparedNativeSessionRedactionPlan, PreparedSearch, SESSION_CALLER_INPUTS_JSON_MAX_BYTES, SESSION_CALLER_MAX_INPUTS, assertNativeBindingVersion, assertNativePipelineSupported, convert_external_detection_batch, createNativeAnonymizerFromConfig, createNativeAnonymizerFromPackage, createNativePipelineFromConfig, createNativePipelineFromPackage, createPipelineContext, deanonymise, defaultPackageUrl, diagnostics_json, diagnostics_stream_json, encodeNativeSearchConfig, encodeNativeSearchConfigInput, exportRedactionKey, getBinding, getDefaultPipeline, getNativeBindingVersion, getNativePipelineCompatibility, inspect_pdf_json, isNativeAnonymizeBinding, loadDefaultPipeline, loadPipeline, load_prepared_package, native_package_version, normalize_for_search, prepareNativePipelineConfig, prepareNativePipelinePackage, prepareNativeSearchPackage, prepare_search_package, redactDefaultText, redactDefaultTextJson, redact_text, redact_text_json, redact_text_stream_json, summary_diagnostics_json };
1685
+ export { CALLER_DETECTION_CONTRACT_VERSION, CALLER_DETECTION_MAX_COUNT, CALLER_DETECTION_REQUEST_JSON_MAX_BYTES, CALLER_DETECTION_TEXT_MAX_BYTES, CAPABILITY_MANIFEST, CAPABILITY_MANIFEST_SCHEMA_VERSION, CAPABILITY_PARITY_PROFILES, CAPABILITY_RUNTIMES, CAPABILITY_SURFACES, DEFAULT_ENTITY_LABELS, DETECTION_SOURCES, DETECTOR_PRIORITY, ENTITY_CAPABILITIES, ENTITY_LABELS, ENTITY_SELECTIONS, EXTERNAL_DETECTION_BATCH_MAX_BYTES, EXTERNAL_DETECTION_BATCH_VERSION, EXTERNAL_DETECTION_DOCUMENT_MAX_BYTES, EXTERNAL_DETECTION_MAX_DETECTIONS, EXTERNAL_DETECTION_MAX_LABEL_MAPPINGS, EXTERNAL_DETECTION_MAX_METADATA_BYTES, EXTERNAL_DETECTION_OFFSET_UNITS, EXTERNAL_DETECTION_PROVIDER_ID_MAX_BYTES, NATIVE_BINDING_PARITY_MEMBERS, OPERATOR_TYPES, PreparedAnonymizer, PreparedNativeAnonymizer, PreparedNativePipeline, PreparedNativeRedactionSession, PreparedNativeSessionRedactionPlan, PreparedSearch, SESSION_CALLER_INPUTS_JSON_MAX_BYTES, SESSION_CALLER_MAX_INPUTS, SUPPORTED_LANGUAGES, assertNativeBindingVersion, assertNativePipelineSupported, convert_external_detection_batch, createNativeAnonymizerFromConfig, createNativeAnonymizerFromPackage, createNativePipelineFromConfig, createNativePipelineFromPackage, createPipeline, createPipelineContext, create_pipeline, deanonymise, defaultPackageUrl, diagnostics_json, diagnostics_stream_json, encodeNativeSearchConfig, encodeNativeSearchConfigInput, exportRedactionKey, getBinding, getDefaultPipeline, getNativeBindingVersion, getNativePipelineCompatibility, inspect_pdf_json, isNativeAnonymizeBinding, loadDefaultPipeline, loadPipeline, load_prepared_package, native_package_version, normalize_for_search, prepareNativePipelineConfig, prepareNativePipelinePackage, prepareNativeSearchPackage, prepare_search_package, redactDefaultText, redactDefaultTextJson, redact_text, redact_text_json, redact_text_stream_json, summary_diagnostics_json };
1449
1686
 
1450
1687
  //# sourceMappingURL=wasm.mjs.map