@easyling/sanity-auto-translate 0.0.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/README.md +748 -0
- package/dist/config.d.ts +55 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/index.d.ts +109 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/logger.d.ts +73 -0
- package/dist/logger.d.ts.map +1 -0
- package/package.json +71 -0
- package/sanity.function.json +9 -0
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration module for Sanity Function
|
|
3
|
+
*
|
|
4
|
+
* Loads and validates configuration from Sanity dataset using UnifiedConfigStorage.
|
|
5
|
+
* Configuration is shared with the Studio plugin and stored in the
|
|
6
|
+
* EL_PluginConfiguration document.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
import type { SanityClient } from '@sanity/client';
|
|
11
|
+
import type { UnifiedPluginConfig } from '@easyling/sanity-connector-shared';
|
|
12
|
+
/**
|
|
13
|
+
* Thrown when the plugin configuration document is missing or invalid.
|
|
14
|
+
*/
|
|
15
|
+
export declare class ConfigurationError extends Error {
|
|
16
|
+
constructor(message: string);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Validated, ready-to-use function configuration extracted from the
|
|
20
|
+
* unified plugin config document.
|
|
21
|
+
*/
|
|
22
|
+
export interface FunctionConfig {
|
|
23
|
+
/** Enabled target locale codes */
|
|
24
|
+
targetLocales: string[];
|
|
25
|
+
/** Source language code (optional) */
|
|
26
|
+
sourceLocale?: string;
|
|
27
|
+
/** OAuth project ID */
|
|
28
|
+
projectId: string;
|
|
29
|
+
/** OAuth access token */
|
|
30
|
+
accessToken: string;
|
|
31
|
+
/** Translation API endpoint */
|
|
32
|
+
translationEndpoint: string;
|
|
33
|
+
/** Document types to auto-translate */
|
|
34
|
+
autoTranslateDocumentTypes: string[];
|
|
35
|
+
/** Request content type */
|
|
36
|
+
requestContentType: 'application/json' | 'application/x-protobuf';
|
|
37
|
+
/** Response accept header */
|
|
38
|
+
responseAcceptHeader: 'application/json' | 'application/x-protobuf';
|
|
39
|
+
/** Default document creation mode */
|
|
40
|
+
defaultDocumentCreationMode: 'draft' | 'published';
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Load the unified plugin configuration from the Sanity dataset.
|
|
44
|
+
*
|
|
45
|
+
* @param client - A configured Sanity client (created from `context.clientOptions`)
|
|
46
|
+
* @returns The raw config document, or `null` if none exists
|
|
47
|
+
*/
|
|
48
|
+
export declare function loadConfiguration(client: SanityClient): Promise<UnifiedPluginConfig | null>;
|
|
49
|
+
/**
|
|
50
|
+
* Validate the raw config and extract the fields required by the function.
|
|
51
|
+
*
|
|
52
|
+
* @throws {ConfigurationError} when required fields are missing or invalid
|
|
53
|
+
*/
|
|
54
|
+
export declare function validateConfiguration(config: UnifiedPluginConfig | null): FunctionConfig;
|
|
55
|
+
//# sourceMappingURL=config.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAE7E;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,KAAK;gBAC/B,OAAO,EAAE,MAAM;CAI5B;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,kCAAkC;IAClC,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,sCAAsC;IACtC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,uBAAuB;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,yBAAyB;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,+BAA+B;IAC/B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,uCAAuC;IACvC,0BAA0B,EAAE,MAAM,EAAE,CAAC;IACrC,2BAA2B;IAC3B,kBAAkB,EAAE,kBAAkB,GAAG,wBAAwB,CAAC;IAClE,6BAA6B;IAC7B,oBAAoB,EAAE,kBAAkB,GAAG,wBAAwB,CAAC;IACpE,qCAAqC;IACrC,2BAA2B,EAAE,OAAO,GAAG,WAAW,CAAC;CACpD;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,mBAAmB,GAAG,IAAI,CAAC,CAGrC;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,mBAAmB,GAAG,IAAI,GACjC,cAAc,CAoChB"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sanity Function for automatic document translation on publish
|
|
3
|
+
*
|
|
4
|
+
* Hooks into the document.publish lifecycle event and automatically
|
|
5
|
+
* translates documents to configured target languages using the shared
|
|
6
|
+
* translation services.
|
|
7
|
+
*
|
|
8
|
+
* @module @easyling/sanity-function-auto-translate
|
|
9
|
+
*/
|
|
10
|
+
import type { FunctionConfig } from './config';
|
|
11
|
+
/**
|
|
12
|
+
* Shape of `context.clientOptions` provided by the Sanity Functions runtime.
|
|
13
|
+
*/
|
|
14
|
+
export interface SanityClientOptions {
|
|
15
|
+
projectId: string;
|
|
16
|
+
dataset: string;
|
|
17
|
+
apiHost?: string;
|
|
18
|
+
token?: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The context object every Sanity Function handler receives.
|
|
22
|
+
*/
|
|
23
|
+
export interface FunctionContext {
|
|
24
|
+
clientOptions: SanityClientOptions;
|
|
25
|
+
/** `true` when running locally via the Sanity CLI */
|
|
26
|
+
local?: boolean;
|
|
27
|
+
eventResourceType?: string;
|
|
28
|
+
eventResourceId?: string;
|
|
29
|
+
functionResourceType?: string;
|
|
30
|
+
functionResourceId?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* The event payload for a `document.publish` trigger.
|
|
34
|
+
* `data` contains the full published Sanity document.
|
|
35
|
+
*/
|
|
36
|
+
export interface PublishEvent {
|
|
37
|
+
data: SanityDocument;
|
|
38
|
+
}
|
|
39
|
+
/** Minimal Sanity document shape. */
|
|
40
|
+
export interface SanityDocument {
|
|
41
|
+
_id: string;
|
|
42
|
+
_type: string;
|
|
43
|
+
_createdAt: string;
|
|
44
|
+
_updatedAt: string;
|
|
45
|
+
_rev: string;
|
|
46
|
+
[key: string]: unknown;
|
|
47
|
+
}
|
|
48
|
+
/** Translation result for a single locale. */
|
|
49
|
+
export interface TranslationResult {
|
|
50
|
+
locale: string | undefined;
|
|
51
|
+
documentId?: string;
|
|
52
|
+
success: boolean;
|
|
53
|
+
error?: string;
|
|
54
|
+
}
|
|
55
|
+
/** Metrics for tracking function execution. */
|
|
56
|
+
export interface ExecutionMetrics {
|
|
57
|
+
totalInvocations: number;
|
|
58
|
+
successfulTranslations: number;
|
|
59
|
+
failedTranslations: number;
|
|
60
|
+
skippedTranslations: number;
|
|
61
|
+
localeMetrics: Record<string, {
|
|
62
|
+
successCount: number;
|
|
63
|
+
failureCount: number;
|
|
64
|
+
}>;
|
|
65
|
+
errorsByStage: {
|
|
66
|
+
configurationLoad?: number;
|
|
67
|
+
configurationValidation?: number;
|
|
68
|
+
contentExtraction?: number;
|
|
69
|
+
translationService?: number;
|
|
70
|
+
documentCreation?: number;
|
|
71
|
+
timeout?: number;
|
|
72
|
+
sizeLimit?: number;
|
|
73
|
+
other?: number;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Value returned by the function handler. */
|
|
77
|
+
export interface TranslateOnPublishResult {
|
|
78
|
+
success: boolean;
|
|
79
|
+
skipped?: boolean;
|
|
80
|
+
reason?: string;
|
|
81
|
+
error?: string;
|
|
82
|
+
results?: TranslationResult[];
|
|
83
|
+
summary?: {
|
|
84
|
+
successCount: number;
|
|
85
|
+
failureCount: number;
|
|
86
|
+
totalCount: number;
|
|
87
|
+
partial?: boolean;
|
|
88
|
+
reason?: string;
|
|
89
|
+
};
|
|
90
|
+
elapsedMs?: number;
|
|
91
|
+
documentSizeBytes?: number;
|
|
92
|
+
limitBytes?: number;
|
|
93
|
+
translationCompleted?: boolean;
|
|
94
|
+
metrics: ExecutionMetrics;
|
|
95
|
+
}
|
|
96
|
+
export type { FunctionConfig } from './config';
|
|
97
|
+
export type { LogLevel, LogContext } from './logger';
|
|
98
|
+
/**
|
|
99
|
+
* Determine whether a document should be auto-translated.
|
|
100
|
+
* An empty or missing autoTranslateDocumentTypes list means all types are eligible.
|
|
101
|
+
*/
|
|
102
|
+
export declare function shouldTranslate(document: SanityDocument, config: FunctionConfig): boolean;
|
|
103
|
+
/**
|
|
104
|
+
* Entry-point for the Sanity Function.
|
|
105
|
+
*
|
|
106
|
+
* Called by the Sanity Functions runtime on every `document.publish` event.
|
|
107
|
+
*/
|
|
108
|
+
export default function translateOnPublish(event: PublishEvent, context: FunctionContext): Promise<TranslateOnPublishResult>;
|
|
109
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAWH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAO/C;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,aAAa,EAAE,mBAAmB,CAAC;IACnC,qDAAqD;IACrD,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,cAAc,CAAC;CACtB;AAED,qCAAqC;AACrC,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,8CAA8C;AAC9C,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,+CAA+C;AAC/C,MAAM,WAAW,gBAAgB;IAC/B,gBAAgB,EAAE,MAAM,CAAC;IACzB,sBAAsB,EAAE,MAAM,CAAC;IAC/B,kBAAkB,EAAE,MAAM,CAAC;IAC3B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,YAAY,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC9E,aAAa,EAAE;QACb,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,uBAAuB,CAAC,EAAE,MAAM,CAAC;QACjC,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAC;QAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,SAAS,CAAC,EAAE,MAAM,CAAC;QACnB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,CAAC;CACH;AAED,8CAA8C;AAC9C,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,iBAAiB,EAAE,CAAC;IAC9B,OAAO,CAAC,EAAE;QACR,YAAY,EAAE,MAAM,CAAC;QACrB,YAAY,EAAE,MAAM,CAAC;QACrB,UAAU,EAAE,MAAM,CAAC;QACnB,OAAO,CAAC,EAAE,OAAO,CAAC;QAClB,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC;IACF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,OAAO,EAAE,gBAAgB,CAAC;CAC3B;AAGD,YAAY,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC/C,YAAY,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAoCrD;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,cAAc,EACxB,MAAM,EAAE,cAAc,GACrB,OAAO,CAIT;AAiBD;;;;GAIG;AACH,wBAA8B,kBAAkB,CAC9C,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,wBAAwB,CAAC,CA2WnC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createClient as __WEBPACK_EXTERNAL_MODULE__sanity_client_02883fb2_createClient__}from"@sanity/client";var __webpack_modules__={256(e,t,n){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Metadata=t.TranslatableField=t.Content_FieldsEntry=t.Content=t.TranslationRequestPayload=t.protobufPackage=void 0;const r=o(n(110));function s(e){return null!=e}t.protobufPackage="hu.skawa.pagetranslate.server.model.protobuffers",t.TranslationRequestPayload={encode:(e,n=r.default.Writer.create())=>(void 0!==e.content&&t.Content.encode(e.content,n.uint32(10).fork()).ldelim(),""!==e.project&&n.uint32(34).string(e.project),""!==e.format&&n.uint32(18).string(e.format),void 0!==e.metadata&&t.Metadata.encode(e.metadata,n.uint32(26).fork()).ldelim(),n),decode(e,n){const o=e instanceof r.default.Reader?e:r.default.Reader.create(e);let s=void 0===n?o.len:o.pos+n;const a={content:void 0,project:"",format:"",metadata:void 0};for(;o.pos<s;){const e=o.uint32();switch(e>>>3){case 1:if(10!==e)break;a.content=t.Content.decode(o,o.uint32());continue;case 4:if(34!==e)break;a.project=o.string();continue;case 2:if(18!==e)break;a.format=o.string();continue;case 3:if(26!==e)break;a.metadata=t.Metadata.decode(o,o.uint32());continue}if(4==(7&e)||0===e)break;o.skipType(7&e)}return a},fromJSON:e=>({content:s(e.content)?t.Content.fromJSON(e.content):void 0,project:s(e.project)?globalThis.String(e.project):"",format:s(e.format)?globalThis.String(e.format):"",metadata:s(e.metadata)?t.Metadata.fromJSON(e.metadata):void 0}),toJSON(e){const n={};return void 0!==e.content&&(n.content=t.Content.toJSON(e.content)),""!==e.project&&(n.project=e.project),""!==e.format&&(n.format=e.format),void 0!==e.metadata&&(n.metadata=t.Metadata.toJSON(e.metadata)),n},create:e=>t.TranslationRequestPayload.fromPartial(e??{}),fromPartial(e){const n={content:void 0,project:"",format:"",metadata:void 0};return n.content=void 0!==e.content&&null!==e.content?t.Content.fromPartial(e.content):void 0,n.project=e.project??"",n.format=e.format??"",n.metadata=void 0!==e.metadata&&null!==e.metadata?t.Metadata.fromPartial(e.metadata):void 0,n}},t.Content={encode:(e,n=r.default.Writer.create())=>(""!==e.body&&n.uint32(10).string(e.body),""!==e.title&&n.uint32(18).string(e.title),""!==e.slug&&n.uint32(26).string(e.slug),Object.entries(e.fields).forEach(([e,o])=>{t.Content_FieldsEntry.encode({key:e,value:o},n.uint32(34).fork()).ldelim()}),n),decode(e,n){const o=e instanceof r.default.Reader?e:r.default.Reader.create(e);let s=void 0===n?o.len:o.pos+n;const a={body:"",title:"",slug:"",fields:{}};for(;o.pos<s;){const e=o.uint32();switch(e>>>3){case 1:if(10!==e)break;a.body=o.string();continue;case 2:if(18!==e)break;a.title=o.string();continue;case 3:if(26!==e)break;a.slug=o.string();continue;case 4:if(34!==e)break;const n=t.Content_FieldsEntry.decode(o,o.uint32());void 0!==n.value&&(a.fields[n.key]=n.value);continue}if(4==(7&e)||0===e)break;o.skipType(7&e)}return a},fromJSON(e){return{body:s(e.body)?globalThis.String(e.body):"",title:s(e.title)?globalThis.String(e.title):"",slug:s(e.slug)?globalThis.String(e.slug):"",fields:(n=e.fields,"object"==typeof n&&null!==n?Object.entries(e.fields).reduce((e,[n,o])=>(e[n]=t.TranslatableField.fromJSON(o),e),{}):{})};var n},toJSON(e){const n={};if(""!==e.body&&(n.body=e.body),""!==e.title&&(n.title=e.title),""!==e.slug&&(n.slug=e.slug),e.fields){const o=Object.entries(e.fields);o.length>0&&(n.fields={},o.forEach(([e,o])=>{n.fields[e]=t.TranslatableField.toJSON(o)}))}return n},create:e=>t.Content.fromPartial(e??{}),fromPartial(e){const n={body:"",title:"",slug:"",fields:{}};return n.body=e.body??"",n.title=e.title??"",n.slug=e.slug??"",n.fields=Object.entries(e.fields??{}).reduce((e,[n,o])=>(void 0!==o&&(e[n]=t.TranslatableField.fromPartial(o)),e),{}),n}},t.Content_FieldsEntry={encode:(e,n=r.default.Writer.create())=>(""!==e.key&&n.uint32(10).string(e.key),void 0!==e.value&&t.TranslatableField.encode(e.value,n.uint32(18).fork()).ldelim(),n),decode(e,n){const o=e instanceof r.default.Reader?e:r.default.Reader.create(e);let s=void 0===n?o.len:o.pos+n;const a={key:"",value:void 0};for(;o.pos<s;){const e=o.uint32();switch(e>>>3){case 1:if(10!==e)break;a.key=o.string();continue;case 2:if(18!==e)break;a.value=t.TranslatableField.decode(o,o.uint32());continue}if(4==(7&e)||0===e)break;o.skipType(7&e)}return a},fromJSON:e=>({key:s(e.key)?globalThis.String(e.key):"",value:s(e.value)?t.TranslatableField.fromJSON(e.value):void 0}),toJSON(e){const n={};return""!==e.key&&(n.key=e.key),void 0!==e.value&&(n.value=t.TranslatableField.toJSON(e.value)),n},create:e=>t.Content_FieldsEntry.fromPartial(e??{}),fromPartial(e){const n={key:"",value:void 0};return n.key=e.key??"",n.value=void 0!==e.value&&null!==e.value?t.TranslatableField.fromPartial(e.value):void 0,n}},t.TranslatableField={encode:(e,t=r.default.Writer.create())=>(""!==e.value&&t.uint32(10).string(e.value),!1!==e.dnt&&t.uint32(16).bool(e.dnt),""!==e.type&&t.uint32(26).string(e.type),""!==e.path&&t.uint32(34).string(e.path),t),decode(e,t){const n=e instanceof r.default.Reader?e:r.default.Reader.create(e);let o=void 0===t?n.len:n.pos+t;const s={value:"",dnt:!1,type:"",path:""};for(;n.pos<o;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;s.value=n.string();continue;case 2:if(16!==e)break;s.dnt=n.bool();continue;case 3:if(26!==e)break;s.type=n.string();continue;case 4:if(34!==e)break;s.path=n.string();continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return s},fromJSON:e=>({value:s(e.value)?globalThis.String(e.value):"",dnt:!!s(e.dnt)&&globalThis.Boolean(e.dnt),type:s(e.type)?globalThis.String(e.type):"",path:s(e.path)?globalThis.String(e.path):""}),toJSON(e){const t={};return""!==e.value&&(t.value=e.value),!1!==e.dnt&&(t.dnt=e.dnt),""!==e.type&&(t.type=e.type),""!==e.path&&(t.path=e.path),t},create:e=>t.TranslatableField.fromPartial(e??{}),fromPartial(e){const t={value:"",dnt:!1,type:"",path:""};return t.value=e.value??"",t.dnt=e.dnt??!1,t.type=e.type??"",t.path=e.path??"",t}},t.Metadata={encode(e,t=r.default.Writer.create()){""!==e.documentId&&t.uint32(10).string(e.documentId),""!==e.documentType&&t.uint32(18).string(e.documentType),""!==e.title&&t.uint32(26).string(e.title),""!==e.sourceLanguage&&t.uint32(34).string(e.sourceLanguage),""!==e.targetLanguage&&t.uint32(42).string(e.targetLanguage);for(const n of e.targetLocales)t.uint32(50).string(n);return t},decode(e,t){const n=e instanceof r.default.Reader?e:r.default.Reader.create(e);let o=void 0===t?n.len:n.pos+t;const s={documentId:"",documentType:"",title:"",sourceLanguage:"",targetLanguage:"",targetLocales:[]};for(;n.pos<o;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;s.documentId=n.string();continue;case 2:if(18!==e)break;s.documentType=n.string();continue;case 3:if(26!==e)break;s.title=n.string();continue;case 4:if(34!==e)break;s.sourceLanguage=n.string();continue;case 5:if(42!==e)break;s.targetLanguage=n.string();continue;case 6:if(50!==e)break;s.targetLocales.push(n.string());continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return s},fromJSON:e=>({documentId:s(e.documentId)?globalThis.String(e.documentId):"",documentType:s(e.documentType)?globalThis.String(e.documentType):"",title:s(e.title)?globalThis.String(e.title):"",sourceLanguage:s(e.sourceLanguage)?globalThis.String(e.sourceLanguage):"",targetLanguage:s(e.targetLanguage)?globalThis.String(e.targetLanguage):"",targetLocales:globalThis.Array.isArray(e?.targetLocales)?e.targetLocales.map(e=>globalThis.String(e)):[]}),toJSON(e){const t={};return""!==e.documentId&&(t.documentId=e.documentId),""!==e.documentType&&(t.documentType=e.documentType),""!==e.title&&(t.title=e.title),""!==e.sourceLanguage&&(t.sourceLanguage=e.sourceLanguage),""!==e.targetLanguage&&(t.targetLanguage=e.targetLanguage),e.targetLocales?.length&&(t.targetLocales=e.targetLocales),t},create:e=>t.Metadata.fromPartial(e??{}),fromPartial(e){const t={documentId:"",documentType:"",title:"",sourceLanguage:"",targetLanguage:"",targetLocales:[]};return t.documentId=e.documentId??"",t.documentType=e.documentType??"",t.title=e.title??"",t.sourceLanguage=e.sourceLanguage??"",t.targetLanguage=e.targetLanguage??"",t.targetLocales=e.targetLocales?.map(e=>e)||[],t}}},98(e,t,n){var o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TranslatedDocument_FieldsEntry=t.TranslatedDocument=t.TranslationResponse=t.protobufPackage=void 0;const r=o(n(110)),s=n(256);function a(e){return null!=e}t.protobufPackage="hu.skawa.pagetranslate.server.model.protobuffers",t.TranslationResponse={encode(e,n=r.default.Writer.create()){!1!==e.success&&n.uint32(8).bool(e.success);for(const o of e.translatedDocuments)t.TranslatedDocument.encode(o,n.uint32(18).fork()).ldelim();return""!==e.sourceLocale&&n.uint32(26).string(e.sourceLocale),""!==e.error&&n.uint32(34).string(e.error),""!==e.requestId&&n.uint32(42).string(e.requestId),n},decode(e,n){const o=e instanceof r.default.Reader?e:r.default.Reader.create(e);let s=void 0===n?o.len:o.pos+n;const a={success:!1,translatedDocuments:[],sourceLocale:"",error:"",requestId:""};for(;o.pos<s;){const e=o.uint32();switch(e>>>3){case 1:if(8!==e)break;a.success=o.bool();continue;case 2:if(18!==e)break;a.translatedDocuments.push(t.TranslatedDocument.decode(o,o.uint32()));continue;case 3:if(26!==e)break;a.sourceLocale=o.string();continue;case 4:if(34!==e)break;a.error=o.string();continue;case 5:if(42!==e)break;a.requestId=o.string();continue}if(4==(7&e)||0===e)break;o.skipType(7&e)}return a},fromJSON:e=>({success:!!a(e.success)&&globalThis.Boolean(e.success),translatedDocuments:globalThis.Array.isArray(e?.translatedDocuments)?e.translatedDocuments.map(e=>t.TranslatedDocument.fromJSON(e)):[],sourceLocale:a(e.sourceLocale)?globalThis.String(e.sourceLocale):"",error:a(e.error)?globalThis.String(e.error):"",requestId:a(e.requestId)?globalThis.String(e.requestId):""}),toJSON(e){const n={};return!1!==e.success&&(n.success=e.success),e.translatedDocuments?.length&&(n.translatedDocuments=e.translatedDocuments.map(e=>t.TranslatedDocument.toJSON(e))),""!==e.sourceLocale&&(n.sourceLocale=e.sourceLocale),""!==e.error&&(n.error=e.error),""!==e.requestId&&(n.requestId=e.requestId),n},create:e=>t.TranslationResponse.fromPartial(e??{}),fromPartial(e){const n={success:!1,translatedDocuments:[],sourceLocale:"",error:"",requestId:""};return n.success=e.success??!1,n.translatedDocuments=e.translatedDocuments?.map(e=>t.TranslatedDocument.fromPartial(e))||[],n.sourceLocale=e.sourceLocale??"",n.error=e.error??"",n.requestId=e.requestId??"",n}},t.TranslatedDocument={encode:(e,n=r.default.Writer.create())=>(""!==e.body&&n.uint32(10).string(e.body),""!==e.title&&n.uint32(18).string(e.title),""!==e.slug&&n.uint32(26).string(e.slug),Object.entries(e.fields).forEach(([e,o])=>{t.TranslatedDocument_FieldsEntry.encode({key:e,value:o},n.uint32(34).fork()).ldelim()}),""!==e.locale&&n.uint32(42).string(e.locale),n),decode(e,n){const o=e instanceof r.default.Reader?e:r.default.Reader.create(e);let s=void 0===n?o.len:o.pos+n;const a={body:"",title:"",slug:"",fields:{},locale:""};for(;o.pos<s;){const e=o.uint32();switch(e>>>3){case 1:if(10!==e)break;a.body=o.string();continue;case 2:if(18!==e)break;a.title=o.string();continue;case 3:if(26!==e)break;a.slug=o.string();continue;case 4:if(34!==e)break;const n=t.TranslatedDocument_FieldsEntry.decode(o,o.uint32());void 0!==n.value&&(a.fields[n.key]=n.value);continue;case 5:if(42!==e)break;a.locale=o.string();continue}if(4==(7&e)||0===e)break;o.skipType(7&e)}return a},fromJSON(e){return{body:a(e.body)?globalThis.String(e.body):"",title:a(e.title)?globalThis.String(e.title):"",slug:a(e.slug)?globalThis.String(e.slug):"",fields:(t=e.fields,"object"==typeof t&&null!==t?Object.entries(e.fields).reduce((e,[t,n])=>(e[t]=s.TranslatableField.fromJSON(n),e),{}):{}),locale:a(e.locale)?globalThis.String(e.locale):""};var t},toJSON(e){const t={};if(""!==e.body&&(t.body=e.body),""!==e.title&&(t.title=e.title),""!==e.slug&&(t.slug=e.slug),e.fields){const n=Object.entries(e.fields);n.length>0&&(t.fields={},n.forEach(([e,n])=>{t.fields[e]=s.TranslatableField.toJSON(n)}))}return""!==e.locale&&(t.locale=e.locale),t},create:e=>t.TranslatedDocument.fromPartial(e??{}),fromPartial(e){const t={body:"",title:"",slug:"",fields:{},locale:""};return t.body=e.body??"",t.title=e.title??"",t.slug=e.slug??"",t.fields=Object.entries(e.fields??{}).reduce((e,[t,n])=>(void 0!==n&&(e[t]=s.TranslatableField.fromPartial(n)),e),{}),t.locale=e.locale??"",t}},t.TranslatedDocument_FieldsEntry={encode:(e,t=r.default.Writer.create())=>(""!==e.key&&t.uint32(10).string(e.key),void 0!==e.value&&s.TranslatableField.encode(e.value,t.uint32(18).fork()).ldelim(),t),decode(e,t){const n=e instanceof r.default.Reader?e:r.default.Reader.create(e);let o=void 0===t?n.len:n.pos+t;const a={key:"",value:void 0};for(;n.pos<o;){const e=n.uint32();switch(e>>>3){case 1:if(10!==e)break;a.key=n.string();continue;case 2:if(18!==e)break;a.value=s.TranslatableField.decode(n,n.uint32());continue}if(4==(7&e)||0===e)break;n.skipType(7&e)}return a},fromJSON:e=>({key:a(e.key)?globalThis.String(e.key):"",value:a(e.value)?s.TranslatableField.fromJSON(e.value):void 0}),toJSON(e){const t={};return""!==e.key&&(t.key=e.key),void 0!==e.value&&(t.value=s.TranslatableField.toJSON(e.value)),t},create:e=>t.TranslatedDocument_FieldsEntry.fromPartial(e??{}),fromPartial(e){const t={key:"",value:void 0};return t.key=e.key??"",t.value=void 0!==e.value&&null!==e.value?s.TranslatableField.fromPartial(e.value):void 0,t}}},233(e){e.exports=function(e,t){for(var n=new Array(arguments.length-1),o=0,r=2,s=!0;r<arguments.length;)n[o++]=arguments[r++];return new Promise(function(r,a){n[o]=function(e){if(s)if(s=!1,e)a(e);else{for(var t=new Array(arguments.length-1),n=0;n<t.length;)t[n++]=arguments[n];r.apply(null,t)}};try{e.apply(t||null,n)}catch(e){s&&(s=!1,a(e))}})}},979(e,t){var n=t;n.length=function(e){var t=e.length;if(!t)return 0;for(var n=0;--t%4>1&&"="===e.charAt(t);)++n;return Math.ceil(3*e.length)/4-n};for(var o=new Array(64),r=new Array(123),s=0;s<64;)r[o[s]=s<26?s+65:s<52?s+71:s<62?s-4:s-59|43]=s++;n.encode=function(e,t,n){for(var r,s=null,a=[],i=0,l=0;t<n;){var c=e[t++];switch(l){case 0:a[i++]=o[c>>2],r=(3&c)<<4,l=1;break;case 1:a[i++]=o[r|c>>4],r=(15&c)<<2,l=2;break;case 2:a[i++]=o[r|c>>6],a[i++]=o[63&c],l=0}i>8191&&((s||(s=[])).push(String.fromCharCode.apply(String,a)),i=0)}return l&&(a[i++]=o[r],a[i++]=61,1===l&&(a[i++]=61)),s?(i&&s.push(String.fromCharCode.apply(String,a.slice(0,i))),s.join("")):String.fromCharCode.apply(String,a.slice(0,i))};var a="invalid encoding";n.decode=function(e,t,n){for(var o,s=n,i=0,l=0;l<e.length;){var c=e.charCodeAt(l++);if(61===c&&i>1)break;if(void 0===(c=r[c]))throw Error(a);switch(i){case 0:o=c,i=1;break;case 1:t[n++]=o<<2|(48&c)>>4,o=c,i=2;break;case 2:t[n++]=(15&o)<<4|(60&c)>>2,o=c,i=3;break;case 3:t[n++]=(3&o)<<6|c,i=0}}if(1===i)throw Error(a);return n-s},n.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}},474(e){function t(){this._listeners={}}e.exports=t,t.prototype.on=function(e,t,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:n||this}),this},t.prototype.off=function(e,t){if(void 0===e)this._listeners={};else if(void 0===t)this._listeners[e]=[];else for(var n=this._listeners[e],o=0;o<n.length;)n[o].fn===t?n.splice(o,1):++o;return this},t.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var n=[],o=1;o<arguments.length;)n.push(arguments[o++]);for(o=0;o<t.length;)t[o].fn.apply(t[o++].ctx,n)}return this}},750(e){function t(e){return"undefined"!=typeof Float32Array?function(){var t=new Float32Array([-0]),n=new Uint8Array(t.buffer),o=128===n[3];function r(e,o,r){t[0]=e,o[r]=n[0],o[r+1]=n[1],o[r+2]=n[2],o[r+3]=n[3]}function s(e,o,r){t[0]=e,o[r]=n[3],o[r+1]=n[2],o[r+2]=n[1],o[r+3]=n[0]}function a(e,o){return n[0]=e[o],n[1]=e[o+1],n[2]=e[o+2],n[3]=e[o+3],t[0]}function i(e,o){return n[3]=e[o],n[2]=e[o+1],n[1]=e[o+2],n[0]=e[o+3],t[0]}e.writeFloatLE=o?r:s,e.writeFloatBE=o?s:r,e.readFloatLE=o?a:i,e.readFloatBE=o?i:a}():function(){function t(e,t,n,o){var r=t<0?1:0;if(r&&(t=-t),0===t)e(1/t>0?0:2147483648,n,o);else if(isNaN(t))e(2143289344,n,o);else if(t>34028234663852886e22)e((r<<31|2139095040)>>>0,n,o);else if(t<11754943508222875e-54)e((r<<31|Math.round(t/1401298464324817e-60))>>>0,n,o);else{var s=Math.floor(Math.log(t)/Math.LN2);e((r<<31|s+127<<23|8388607&Math.round(t*Math.pow(2,-s)*8388608))>>>0,n,o)}}function a(e,t,n){var o=e(t,n),r=2*(o>>31)+1,s=o>>>23&255,a=8388607&o;return 255===s?a?NaN:r*(1/0):0===s?1401298464324817e-60*r*a:r*Math.pow(2,s-150)*(a+8388608)}e.writeFloatLE=t.bind(null,n),e.writeFloatBE=t.bind(null,o),e.readFloatLE=a.bind(null,r),e.readFloatBE=a.bind(null,s)}(),"undefined"!=typeof Float64Array?function(){var t=new Float64Array([-0]),n=new Uint8Array(t.buffer),o=128===n[7];function r(e,o,r){t[0]=e,o[r]=n[0],o[r+1]=n[1],o[r+2]=n[2],o[r+3]=n[3],o[r+4]=n[4],o[r+5]=n[5],o[r+6]=n[6],o[r+7]=n[7]}function s(e,o,r){t[0]=e,o[r]=n[7],o[r+1]=n[6],o[r+2]=n[5],o[r+3]=n[4],o[r+4]=n[3],o[r+5]=n[2],o[r+6]=n[1],o[r+7]=n[0]}function a(e,o){return n[0]=e[o],n[1]=e[o+1],n[2]=e[o+2],n[3]=e[o+3],n[4]=e[o+4],n[5]=e[o+5],n[6]=e[o+6],n[7]=e[o+7],t[0]}function i(e,o){return n[7]=e[o],n[6]=e[o+1],n[5]=e[o+2],n[4]=e[o+3],n[3]=e[o+4],n[2]=e[o+5],n[1]=e[o+6],n[0]=e[o+7],t[0]}e.writeDoubleLE=o?r:s,e.writeDoubleBE=o?s:r,e.readDoubleLE=o?a:i,e.readDoubleBE=o?i:a}():function(){function t(e,t,n,o,r,s){var a=o<0?1:0;if(a&&(o=-o),0===o)e(0,r,s+t),e(1/o>0?0:2147483648,r,s+n);else if(isNaN(o))e(0,r,s+t),e(2146959360,r,s+n);else if(o>17976931348623157e292)e(0,r,s+t),e((a<<31|2146435072)>>>0,r,s+n);else{var i;if(o<22250738585072014e-324)e((i=o/5e-324)>>>0,r,s+t),e((a<<31|i/4294967296)>>>0,r,s+n);else{var l=Math.floor(Math.log(o)/Math.LN2);1024===l&&(l=1023),e(4503599627370496*(i=o*Math.pow(2,-l))>>>0,r,s+t),e((a<<31|l+1023<<20|1048576*i&1048575)>>>0,r,s+n)}}}function a(e,t,n,o,r){var s=e(o,r+t),a=e(o,r+n),i=2*(a>>31)+1,l=a>>>20&2047,c=4294967296*(1048575&a)+s;return 2047===l?c?NaN:i*(1/0):0===l?5e-324*i*c:i*Math.pow(2,l-1075)*(c+4503599627370496)}e.writeDoubleLE=t.bind(null,n,0,4),e.writeDoubleBE=t.bind(null,o,4,0),e.readDoubleLE=a.bind(null,r,0,4),e.readDoubleBE=a.bind(null,s,4,0)}(),e}function n(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}function o(e,t,n){t[n]=e>>>24,t[n+1]=e>>>16&255,t[n+2]=e>>>8&255,t[n+3]=255&e}function r(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0}function s(e,t){return(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0}e.exports=t(t)},925(module){function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(e){}return null}module.exports=inquire},226(e){e.exports=function(e,t,n){var o=n||8192,r=o>>>1,s=null,a=o;return function(n){if(n<1||n>r)return e(n);a+n>o&&(s=e(o),a=0);var i=t.call(s,a,a+=n);return 7&a&&(a=1+(7|a)),i}}},971(e,t){var n=t;n.length=function(e){for(var t=0,n=0,o=0;o<e.length;++o)(n=e.charCodeAt(o))<128?t+=1:n<2048?t+=2:55296==(64512&n)&&56320==(64512&e.charCodeAt(o+1))?(++o,t+=4):t+=3;return t},n.read=function(e,t,n){if(n-t<1)return"";for(var o,r=null,s=[],a=0;t<n;)(o=e[t++])<128?s[a++]=o:o>191&&o<224?s[a++]=(31&o)<<6|63&e[t++]:o>239&&o<365?(o=((7&o)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,s[a++]=55296+(o>>10),s[a++]=56320+(1023&o)):s[a++]=(15&o)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,s)),a=0);return r?(a&&r.push(String.fromCharCode.apply(String,s.slice(0,a))),r.join("")):String.fromCharCode.apply(String,s.slice(0,a))},n.write=function(e,t,n){for(var o,r,s=n,a=0;a<e.length;++a)(o=e.charCodeAt(a))<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=63&o|128):55296==(64512&o)&&56320==(64512&(r=e.charCodeAt(a+1)))?(o=65536+((1023&o)<<10)+(1023&r),++a,t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=63&o|128):(t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=63&o|128);return n-s}},110(e,t,n){e.exports=n(134)},134(e,t,n){var o=t;function r(){o.util._configure(),o.Writer._configure(o.BufferWriter),o.Reader._configure(o.BufferReader)}o.build="minimal",o.Writer=n(301),o.BufferWriter=n(422),o.Reader=n(137),o.BufferReader=n(10),o.util=n(382),o.rpc=n(691),o.roots=n(381),o.configure=r,r()},137(e,t,n){e.exports=l;var o,r=n(382),s=r.LongBits,a=r.utf8;function i(e,t){return RangeError("index out of range: "+e.pos+" + "+(t||1)+" > "+e.len)}function l(e){this.buf=e,this.pos=0,this.len=e.length}var c,u="undefined"!=typeof Uint8Array?function(e){if(e instanceof Uint8Array||Array.isArray(e))return new l(e);throw Error("illegal buffer")}:function(e){if(Array.isArray(e))return new l(e);throw Error("illegal buffer")},d=function(){return r.Buffer?function(e){return(l.create=function(e){return r.Buffer.isBuffer(e)?new o(e):u(e)})(e)}:u};function f(){var e=new s(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw i(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw i(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}function p(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}function h(){if(this.pos+8>this.len)throw i(this,8);return new s(p(this.buf,this.pos+=4),p(this.buf,this.pos+=4))}l.create=d(),l.prototype._slice=r.Array.prototype.subarray||r.Array.prototype.slice,l.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return c;if((this.pos+=5)>this.len)throw this.pos=this.len,i(this,10);return c}),l.prototype.int32=function(){return 0|this.uint32()},l.prototype.sint32=function(){var e=this.uint32();return e>>>1^-(1&e)},l.prototype.bool=function(){return 0!==this.uint32()},l.prototype.fixed32=function(){if(this.pos+4>this.len)throw i(this,4);return p(this.buf,this.pos+=4)},l.prototype.sfixed32=function(){if(this.pos+4>this.len)throw i(this,4);return 0|p(this.buf,this.pos+=4)},l.prototype.float=function(){if(this.pos+4>this.len)throw i(this,4);var e=r.float.readFloatLE(this.buf,this.pos);return this.pos+=4,e},l.prototype.double=function(){if(this.pos+8>this.len)throw i(this,4);var e=r.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,e},l.prototype.bytes=function(){var e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw i(this,e);if(this.pos+=e,Array.isArray(this.buf))return this.buf.slice(t,n);if(t===n){var o=r.Buffer;return o?o.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,t,n)},l.prototype.string=function(){var e=this.bytes();return a.read(e,0,e.length)},l.prototype.skip=function(e){if("number"==typeof e){if(this.pos+e>this.len)throw i(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw i(this)}while(128&this.buf[this.pos++]);return this},l.prototype.skipType=function(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+e+" at offset "+this.pos)}return this},l._configure=function(e){o=e,l.create=d(),o._configure();var t=r.Long?"toLong":"toNumber";r.merge(l.prototype,{int64:function(){return f.call(this)[t](!1)},uint64:function(){return f.call(this)[t](!0)},sint64:function(){return f.call(this).zzDecode()[t](!1)},fixed64:function(){return h.call(this)[t](!0)},sfixed64:function(){return h.call(this)[t](!1)}})}},10(e,t,n){e.exports=s;var o=n(137);(s.prototype=Object.create(o.prototype)).constructor=s;var r=n(382);function s(e){o.call(this,e)}s._configure=function(){r.Buffer&&(s.prototype._slice=r.Buffer.prototype.slice)},s.prototype.string=function(){var e=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+e,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+e,this.len))},s._configure()},381(e){e.exports={}},691(e,t,n){t.Service=n(447)},447(e,t,n){e.exports=r;var o=n(382);function r(e,t,n){if("function"!=typeof e)throw TypeError("rpcImpl must be a function");o.EventEmitter.call(this),this.rpcImpl=e,this.requestDelimited=Boolean(t),this.responseDelimited=Boolean(n)}(r.prototype=Object.create(o.EventEmitter.prototype)).constructor=r,r.prototype.rpcCall=function e(t,n,r,s,a){if(!s)throw TypeError("request must be specified");var i=this;if(!a)return o.asPromise(e,i,t,n,r,s);if(i.rpcImpl)try{return i.rpcImpl(t,n[i.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(e,n){if(e)return i.emit("error",e,t),a(e);if(null!==n){if(!(n instanceof r))try{n=r[i.responseDelimited?"decodeDelimited":"decode"](n)}catch(e){return i.emit("error",e,t),a(e)}return i.emit("data",n,t),a(null,n)}i.end(!0)})}catch(e){return i.emit("error",e,t),void setTimeout(function(){a(e)},0)}else setTimeout(function(){a(Error("already ended"))},0)},r.prototype.end=function(e){return this.rpcImpl&&(e||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},3(e,t,n){e.exports=r;var o=n(382);function r(e,t){this.lo=e>>>0,this.hi=t>>>0}var s=r.zero=new r(0,0);s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1};var a=r.zeroHash="\0\0\0\0\0\0\0\0";r.fromNumber=function(e){if(0===e)return s;var t=e<0;t&&(e=-e);var n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)},r.from=function(e){if("number"==typeof e)return r.fromNumber(e);if(o.isString(e)){if(!o.Long)return r.fromNumber(parseInt(e,10));e=o.Long.fromString(e)}return e.low||e.high?new r(e.low>>>0,e.high>>>0):s},r.prototype.toNumber=function(e){if(!e&&this.hi>>>31){var t=1+~this.lo>>>0,n=~this.hi>>>0;return t||(n=n+1>>>0),-(t+4294967296*n)}return this.lo+4294967296*this.hi},r.prototype.toLong=function(e){return o.Long?new o.Long(0|this.lo,0|this.hi,Boolean(e)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(e)}};var i=String.prototype.charCodeAt;r.fromHash=function(e){return e===a?s:new r((i.call(e,0)|i.call(e,1)<<8|i.call(e,2)<<16|i.call(e,3)<<24)>>>0,(i.call(e,4)|i.call(e,5)<<8|i.call(e,6)<<16|i.call(e,7)<<24)>>>0)},r.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},r.prototype.zzEncode=function(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this},r.prototype.zzDecode=function(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this},r.prototype.length=function(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}},382(e,t,n){var o=t;function r(e,t,n){for(var o=Object.keys(t),r=0;r<o.length;++r)void 0!==e[o[r]]&&n||(e[o[r]]=t[o[r]]);return e}function s(e){function t(e,n){if(!(this instanceof t))return new t(e,n);Object.defineProperty(this,"message",{get:function(){return e}}),Error.captureStackTrace?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:(new Error).stack||""}),n&&r(this,n)}return t.prototype=Object.create(Error.prototype,{constructor:{value:t,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return e},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),t}o.asPromise=n(233),o.base64=n(979),o.EventEmitter=n(474),o.float=n(750),o.inquire=n(925),o.utf8=n(971),o.pool=n(226),o.LongBits=n(3),o.isNode=Boolean("undefined"!=typeof global&&global&&global.process&&global.process.versions&&global.process.versions.node),o.global=o.isNode&&global||"undefined"!=typeof window&&window||"undefined"!=typeof self&&self||this,o.emptyArray=Object.freeze?Object.freeze([]):[],o.emptyObject=Object.freeze?Object.freeze({}):{},o.isInteger=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},o.isString=function(e){return"string"==typeof e||e instanceof String},o.isObject=function(e){return e&&"object"==typeof e},o.isset=o.isSet=function(e,t){var n=e[t];return!(null==n||!e.hasOwnProperty(t))&&("object"!=typeof n||(Array.isArray(n)?n.length:Object.keys(n).length)>0)},o.Buffer=function(){try{var e=o.inquire("buffer").Buffer;return e.prototype.utf8Write?e:null}catch(e){return null}}(),o._Buffer_from=null,o._Buffer_allocUnsafe=null,o.newBuffer=function(e){return"number"==typeof e?o.Buffer?o._Buffer_allocUnsafe(e):new o.Array(e):o.Buffer?o._Buffer_from(e):"undefined"==typeof Uint8Array?e:new Uint8Array(e)},o.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,o.Long=o.global.dcodeIO&&o.global.dcodeIO.Long||o.global.Long||o.inquire("long"),o.key2Re=/^true|false|0|1$/,o.key32Re=/^-?(?:0|[1-9][0-9]*)$/,o.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,o.longToHash=function(e){return e?o.LongBits.from(e).toHash():o.LongBits.zeroHash},o.longFromHash=function(e,t){var n=o.LongBits.fromHash(e);return o.Long?o.Long.fromBits(n.lo,n.hi,t):n.toNumber(Boolean(t))},o.merge=r,o.lcFirst=function(e){return e.charAt(0).toLowerCase()+e.substring(1)},o.newError=s,o.ProtocolError=s("ProtocolError"),o.oneOfGetter=function(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=1;return function(){for(var e=Object.keys(this),n=e.length-1;n>-1;--n)if(1===t[e[n]]&&void 0!==this[e[n]]&&null!==this[e[n]])return e[n]}},o.oneOfSetter=function(e){return function(t){for(var n=0;n<e.length;++n)e[n]!==t&&delete this[e[n]]}},o.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},o._configure=function(){var e=o.Buffer;e?(o._Buffer_from=e.from!==Uint8Array.from&&e.from||function(t,n){return new e(t,n)},o._Buffer_allocUnsafe=e.allocUnsafe||function(t){return new e(t)}):o._Buffer_from=o._Buffer_allocUnsafe=null}},301(e,t,n){e.exports=d;var o,r=n(382),s=r.LongBits,a=r.base64,i=r.utf8;function l(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}function c(){}function u(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}function d(){this.len=0,this.head=new l(c,0,0),this.tail=this.head,this.states=null}var f=function(){return r.Buffer?function(){return(d.create=function(){return new o})()}:function(){return new d}};function p(e,t,n){t[n]=255&e}function h(e,t){this.len=e,this.next=void 0,this.val=t}function g(e,t,n){for(;e.hi;)t[n++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[n++]=127&e.lo|128,e.lo=e.lo>>>7;t[n++]=e.lo}function m(e,t,n){t[n]=255&e,t[n+1]=e>>>8&255,t[n+2]=e>>>16&255,t[n+3]=e>>>24}d.create=f(),d.alloc=function(e){return new r.Array(e)},r.Array!==Array&&(d.alloc=r.pool(d.alloc,r.Array.prototype.subarray)),d.prototype._push=function(e,t,n){return this.tail=this.tail.next=new l(e,t,n),this.len+=t,this},h.prototype=Object.create(l.prototype),h.prototype.fn=function(e,t,n){for(;e>127;)t[n++]=127&e|128,e>>>=7;t[n]=e},d.prototype.uint32=function(e){return this.len+=(this.tail=this.tail.next=new h((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this},d.prototype.int32=function(e){return e<0?this._push(g,10,s.fromNumber(e)):this.uint32(e)},d.prototype.sint32=function(e){return this.uint32((e<<1^e>>31)>>>0)},d.prototype.uint64=function(e){var t=s.from(e);return this._push(g,t.length(),t)},d.prototype.int64=d.prototype.uint64,d.prototype.sint64=function(e){var t=s.from(e).zzEncode();return this._push(g,t.length(),t)},d.prototype.bool=function(e){return this._push(p,1,e?1:0)},d.prototype.fixed32=function(e){return this._push(m,4,e>>>0)},d.prototype.sfixed32=d.prototype.fixed32,d.prototype.fixed64=function(e){var t=s.from(e);return this._push(m,4,t.lo)._push(m,4,t.hi)},d.prototype.sfixed64=d.prototype.fixed64,d.prototype.float=function(e){return this._push(r.float.writeFloatLE,4,e)},d.prototype.double=function(e){return this._push(r.float.writeDoubleLE,8,e)};var y=r.Array.prototype.set?function(e,t,n){t.set(e,n)}:function(e,t,n){for(var o=0;o<e.length;++o)t[n+o]=e[o]};d.prototype.bytes=function(e){var t=e.length>>>0;if(!t)return this._push(p,1,0);if(r.isString(e)){var n=d.alloc(t=a.length(e));a.decode(e,n,0),e=n}return this.uint32(t)._push(y,t,e)},d.prototype.string=function(e){var t=i.length(e);return t?this.uint32(t)._push(i.write,t,e):this._push(p,1,0)},d.prototype.fork=function(){return this.states=new u(this),this.head=this.tail=new l(c,0,0),this.len=0,this},d.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new l(c,0,0),this.len=0),this},d.prototype.ldelim=function(){var e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=e.next,this.tail=t,this.len+=n),this},d.prototype.finish=function(){for(var e=this.head.next,t=this.constructor.alloc(this.len),n=0;e;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t},d._configure=function(e){o=e,d.create=f(),o._configure()}},422(e,t,n){e.exports=s;var o=n(301);(s.prototype=Object.create(o.prototype)).constructor=s;var r=n(382);function s(){o.call(this)}function a(e,t,n){e.length<40?r.utf8.write(e,t,n):t.utf8Write?t.utf8Write(e,n):t.write(e,n)}s._configure=function(){s.alloc=r._Buffer_allocUnsafe,s.writeBytesBuffer=r.Buffer&&r.Buffer.prototype instanceof Uint8Array&&"set"===r.Buffer.prototype.set.name?function(e,t,n){t.set(e,n)}:function(e,t,n){if(e.copy)e.copy(t,n,0,e.length);else for(var o=0;o<e.length;)t[n++]=e[o++]}},s.prototype.bytes=function(e){r.isString(e)&&(e=r._Buffer_from(e,"base64"));var t=e.length>>>0;return this.uint32(t),t&&this._push(s.writeBytesBuffer,t,e),this},s.prototype.string=function(e){var t=r.Buffer.byteLength(e);return this.uint32(t),t&&this._push(a,t,e),this},s._configure()}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(n.exports,n,n.exports,__webpack_require__),n.exports}__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var __webpack_exports__={};function computeDNTDefault(e){const t=["author","contributor","date","time","lastModification","lastModified","_key","_ref","_type","_id","_rev","_createdAt","_updatedAt"],n=["date","time"];if(e.fieldType&&["date","datetime","reference","image","file","geopoint","number","boolean"].includes(e.fieldType))return{shouldBeDNT:!0,reason:`Field type '${e.fieldType}' is non-translatable`};const o=e.fieldName.toLowerCase();for(const e of t)if(o.includes(e.toLowerCase()))return{shouldBeDNT:!0,reason:`Field name contains DNT pattern '${e}'`};if(e.groupName){const t=e.groupName.toLowerCase();for(const e of n)if(t.includes(e.toLowerCase()))return{shouldBeDNT:!0,reason:`Group name contains DNT pattern '${e}'`}}if(e.fieldsetName){const t=e.fieldsetName.toLowerCase();for(const e of n)if(t.includes(e.toLowerCase()))return{shouldBeDNT:!0,reason:`Fieldset name contains DNT pattern '${e}'`}}return{shouldBeDNT:!1,reason:"No DNT patterns matched"}}const ATOMIC_SANITY_TYPES=new Set(["slug","date","datetime","reference","image","file","geopoint","color","block","span"]);function buildGroqPath(e,t){return`*[_type == "${e.documentType}" && _id == $documentId][0].${t}`}class ContentExtractor{inferSanityType(e){if(null==e)return"undefined";if("object"==typeof e&&!Array.isArray(e)){const t=e;if(t._type)return t._type}return"string"==typeof e?"string":"number"==typeof e?"number":"boolean"==typeof e?"boolean":Array.isArray(e)?"array":"object"==typeof e?"object":"unknown"}isSanitySpecialType(e){if(!e||"object"!=typeof e||Array.isArray(e))return!1;const t=e;return!(!t._type||!ATOMIC_SANITY_TYPES.has(t._type))}shouldFlattenObject(e){return!(!e||"object"!=typeof e||Array.isArray(e)||this.isSanitySpecialType(e))}flattenObjectToFields(e,t,n,o){for(const[r,s]of Object.entries(e)){if(r.startsWith("_"))continue;const e=t?`${t}.${r}`:r;null!=s&&(Array.isArray(s)?this.flattenArrayToFields(s,e,r,n,o):"object"!=typeof s||!s._type||ATOMIC_SANITY_TYPES.has(s._type)?this.shouldFlattenObject(s)?this.flattenObjectToFields(s,e,n,o):this.addLeafField(r,s,e,n,o):this.flattenObjectToFields(s,e,n,o))}}flattenArrayToFields(e,t,n,o,r){if(e.every(e=>e&&"object"==typeof e&&"block"===e._type)){const s=this.processArray(n,e),a=computeDNTDefault({fieldPath:t,fieldName:n,fieldType:"block"});return void(o[t]={value:s,dnt:a.shouldBeDNT,type:"block",path:buildGroqPath(r,t)})}if(e.every(e=>e&&"object"==typeof e&&"reference"===e._type))return void(o[t]={value:JSON.stringify(e),dnt:!0,type:"array",path:buildGroqPath(r,t)});if(e.every(e=>e&&"object"==typeof e&&e._key)){for(const s of e){const e=`${t}[_key == "${s._key}"]`;s._type&&!ATOMIC_SANITY_TYPES.has(s._type)?this.flattenObjectToFields(s,e,o,r):s._type?this.addLeafField(n,s,e,o,r):this.flattenObjectToFields(s,e,o,r)}return}const s=computeDNTDefault({fieldPath:t,fieldName:n,fieldType:"array"});o[t]={value:JSON.stringify(e),dnt:s.shouldBeDNT,type:"array",path:buildGroqPath(r,t)}}addLeafField(e,t,n,o,r){let s,a;if("object"==typeof t&&null!==t&&"_type"in t&&"slug"===t._type)s=t.current||"",a="slug";else if("object"!=typeof t||null===t||!("_type"in t)||"date"!==t._type&&"datetime"!==t._type)"object"==typeof t?(s=JSON.stringify(t),a=this.inferSanityType(t)):"string"==typeof t?(s=t,a="string"):(s=String(t),a=this.inferSanityType(t));else{const e=t.value||t;s="string"==typeof e?e:JSON.stringify(e),a=t._type}const i=computeDNTDefault({fieldPath:n,fieldName:e,fieldType:a});o[n]={value:s,dnt:i.shouldBeDNT,type:a,path:buildGroqPath(r,n)}}async extractDocumentContent(e){if(!e||!e._id)throw new Error("Invalid document provided");return this.convertToHtml(e)}convertToHtml(e){if(!e)return"";let t="";for(const[n,o]of Object.entries(e))n.startsWith("_")||o&&(t+=this.processField(n,o));return t.trim()}async extractStructuredContent(e,t){if(!e||!e._id)throw new Error("Invalid document provided");const{title:n,foundAtTopLevel:o}=this.extractTitle(e),r=this.extractSlug(e),{bodyContent:s,fields:a,bodyFoundAtTopLevel:i,bodyFieldName:l}=this.separateContentAndFields(e);console.log("[ContentExtractor] extractStructuredContent:",{documentId:e._id,documentType:e._type,extractedTitle:n,titleFoundAtTopLevel:o,bodyFoundAtTopLevel:i,bodyFieldName:l,documentHasTopLevelTitle:"title"in e,documentHasTopLevelBody:"body"in e||"content"in e});const c=e._type||"document",u=await this.applyDNTPreferences(c,a,void 0,t);return{documentId:e._id,title:n,htmlContent:s,slug:r,fields:u,titleFoundAtTopLevel:o,bodyFoundAtTopLevel:i,bodyFieldName:l}}async applyDNTPreferences(e,t,n,o){try{const r=o?await o.getFieldsForType(e):{},s={};for(const[e,o]of Object.entries(t)){const t=e.split(".").pop()||e;let a;o&&"object"==typeof o&&"type"in o&&(a=o.type);const i=n?.[e],l=computeDNTDefault({fieldPath:e,fieldName:t,fieldType:a,groupName:i?.groupName,fieldsetName:i?.fieldsetName}),c=e in r,u=o&&"object"==typeof o&&"dnt"in o?o.dnt:void 0,d=c?r[e]:!0===u||l.shouldBeDNT;if(o&&"object"==typeof o&&"value"in o){const t=o;s[e]={...t,dnt:d}}else s[e]={value:o,dnt:d,type:this.inferSanityType(o)}}return s}catch(n){return console.warn(`Failed to apply DNT preferences for document type ${e}:`,n),t}}async extractBulkContent(e){const t=[];for(const n of e)try{const e=await this.extractDocumentContent(n),{title:o}=this.extractTitle(n);t.push({documentId:n._id,title:o,htmlContent:e})}catch(e){console.warn(`Failed to extract content from document ${n._id}:`,e)}return t}async extractBulkStructuredContent(e,t){const n=[];for(const o of e)try{const e=await this.extractStructuredContent(o,t);n.push(e)}catch(e){console.warn(`Failed to extract structured content from document ${o?._id||"unknown"}:`,e)}return n}processField(e,t){return null==t?"":Array.isArray(t)?this.processArray(e,t):"object"==typeof t?this.processObject(e,t):"string"==typeof t||"number"==typeof t?this.wrapInHtml(e,String(t)):""}processArray(e,t){let n="";if(t.every(e=>e&&"object"==typeof e&&"block"===e._type&&("bullet"===e.listItem||"number"===e.listItem))){const e="number"===t[0]?.listItem?"ol":"ul";n+=`<${e}>`;for(const e of t)"block"===e._type&&(n+=`<li>${this.processPortableTextBlockContent(e)}</li>`);n+=`</${e}>`}else for(const o of t)o&&"object"==typeof o?"block"===o._type?n+=this.processPortableTextBlock(o):n+=this.processObject(e,o):n+=this.wrapInHtml("item",String(o));return n}processPortableTextBlock(e){const t=this.processPortableTextBlockContent(e);switch(e.style||"normal"){case"h1":return`<h1>${t}</h1>`;case"h2":return`<h2>${t}</h2>`;case"h3":return`<h3>${t}</h3>`;case"h4":return`<h4>${t}</h4>`;case"h5":return`<h5>${t}</h5>`;case"h6":return`<h6>${t}</h6>`;case"blockquote":return`<blockquote>${t}</blockquote>`;default:return`<p>${t}</p>`}}processPortableTextBlockContent(e){if(!e.children||!Array.isArray(e.children))return"";let t="";for(const n of e.children)if("span"===n._type&&n.text){let e=n.text;if(n.marks&&Array.isArray(n.marks))for(const t of n.marks)if("string"==typeof t)switch(t){case"strong":e=`<strong>${e}</strong>`;break;case"em":e=`<em>${e}</em>`;break;case"underline":e=`<u>${e}</u>`;break;case"code":e=`<code>${e}</code>`}else if("object"==typeof t&&"link"===t._type){const n=t.href||"#";e=`<a href="${this.escapeHtml(n)}">${e}</a>`}t+=e}return t}processObject(e,t){let n="";if("reference"===t._type&&t._ref)return`<span data-reference="${t._ref}">Referenced content</span>`;if("image"===t._type){const e=t.alt||"Image",n=t.caption||"";return`<figure><img alt="${this.escapeHtml(e)}" />${n?`<figcaption>${this.escapeHtml(n)}</figcaption>`:""}</figure>`}if("file"===t._type){const e=t.title||"File";return`<a href="#" data-file-ref="${t.asset?._ref||""}">${this.escapeHtml(e)}</a>`}if("url"===t._type){const e=t.href||"#",n=t.text||e;return`<a href="${this.escapeHtml(e)}">${this.escapeHtml(n)}</a>`}if("geopoint"===t._type){const e=t.lat||0,n=t.lng||0,o=t.alt||"";return`<span data-geopoint data-lat="${e}" data-lng="${n}" ${o?`data-alt="${o}"`:""}>Location: ${e}, ${n}</span>`}if("slug"===t._type){const e=t.current||"";return`<span data-slug="${this.escapeHtml(e)}">${this.escapeHtml(e)}</span>`}if("date"===t._type||"datetime"===t._type){const e=t.value||t;if("string"==typeof e)return`<time datetime="${e}">${new Date(e).toLocaleDateString()}</time>`}if("color"===t._type){const e=t.hex||"#000000";return`<span data-color="${e}" data-alpha="${void 0!==t.alpha?t.alpha:1}" style="color: ${e}">Color: ${e}</span>`}if("span"===t._type&&t.marks&&Array.isArray(t.marks)){let e=t.text||"";for(const n of t.marks)if("string"==typeof n)switch(n){case"strong":e=`<strong>${e}</strong>`;break;case"em":e=`<em>${e}</em>`;break;case"underline":e=`<u>${e}</u>`;break;case"code":e=`<code>${e}</code>`}else if("object"==typeof n&&"link"===n._type){const t=n.href||"#";e=`<a href="${this.escapeHtml(t)}">${e}</a>`}return e}for(const[e,o]of Object.entries(t))!e.startsWith("_")&&o&&(n+=this.processField(e,o));return n}wrapInHtml(e,t){return`<div class="field-${e.replace(/[^a-zA-Z0-9-_]/g,"")}">${this.escapeHtml(t)}</div>`}separateContentAndFields(e){const t=["body","content"],n=["title","slug","_id","_type","_createdAt","_updatedAt","_rev"];let o,r="",s=!1;const a={},i={documentType:e._type||"document",documentId:e._id};for(const[n,l]of Object.entries(e))n.startsWith("_")||"title"!==n&&"slug"!==n&&l&&(t.includes(n)?(r+=this.processField(n,l),s=!0,o=n):Array.isArray(l)?this.flattenArrayToFields(l,n,n,a,i):"object"==typeof l&&l._type&&!ATOMIC_SANITY_TYPES.has(l._type)||this.shouldFlattenObject(l)?this.flattenObjectToFields(l,n,a,i):this.addLeafField(n,l,n,a,i));if(!r.trim()){const n=this.findBodyInNestedFields(e,t);n&&(r=n.content,s=!1,o=n.fieldPath)}if(!r.trim()){for(const[t,o]of Object.entries(e))t.startsWith("_")||n.includes(t)||!o||(r+=this.processField(t,o));s=!1,o=void 0}return{bodyContent:r.trim(),fields:a,bodyFoundAtTopLevel:s,bodyFieldName:o}}findBodyInNestedFields(e,t,n=""){for(const[o,r]of Object.entries(e)){if(o.startsWith("_"))continue;if(null==r)continue;const e=n?`${n}.${o}`:o;if("object"==typeof r&&!Array.isArray(r)){if(this.isSanitySpecialType(r))continue;for(const n of t)if(r[n]){const t=`${e}.${n}`,o=this.processField(n,r[n]);if(o.trim())return{content:o,fieldPath:t}}const n=this.findBodyInNestedFields(r,t,e);if(n)return n}if(Array.isArray(r))for(const n of r)if(n&&"object"==typeof n&&!this.isSanitySpecialType(n)){for(const o of t)if(n[o]){const t=n._key?`${e}[_key == "${n._key}"].${o}`:`${e}.${o}`,r=this.processField(o,n[o]);if(r.trim())return{content:r,fieldPath:t}}const o=n._key?`${e}[_key == "${n._key}"]`:e,r=this.findBodyInNestedFields(n,t,o);if(r)return r}}return null}extractSlug(e){if(e.slug){if("object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug&&"slug"===e.slug._type)return e.slug.current||"";if("string"==typeof e.slug)return e.slug}const t=["slug","path","url","permalink"];for(const n of t)if(e[n]){if("object"==typeof e[n]&&null!==e[n]&&"_type"in e[n]&&"slug"===e[n]._type)return e[n].current||"";if("string"==typeof e[n])return e[n]}return""}extractTitle(e){const t=["title","name","heading","label"];for(const n of t)if(e[n]&&"string"==typeof e[n])return{title:e[n],foundAtTopLevel:!0};const n=this.findTitleInNestedFields(e,t);return n?{title:n,foundAtTopLevel:!1}:{title:`${e._type} (${e._id})`,foundAtTopLevel:!1}}findTitleInNestedFields(e,t){for(const[n,o]of Object.entries(e))if(!n.startsWith("_")&&null!=o){if("object"==typeof o&&!Array.isArray(o)){if(this.isSanitySpecialType(o))continue;for(const e of t)if(o[e]&&"string"==typeof o[e])return o[e];const e=this.findTitleInNestedFields(o,t);if(e)return e}if(Array.isArray(o))for(const e of o)if(e&&"object"==typeof e&&!this.isSanitySpecialType(e)){for(const n of t)if(e[n]&&"string"==typeof e[n])return e[n];const n=this.findTitleInNestedFields(e,t);if(n)return n}}return null}escapeHtml(e){const t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,e=>t[e])}}var translation_request=__webpack_require__(256),translation_response=__webpack_require__(98);class TranslationService{constructor(e="http://localhost:8275/translate",t="application/json",n="application/json"){this.placeholderEndpoint=e,this.requestContentType=t,this.responseAcceptHeader=n}inferSanityType(e){if(null==e)return"undefined";if("object"==typeof e&&!Array.isArray(e)){const t=e;if(t._type)return t._type}return"string"==typeof e?"string":"number"==typeof e?"number":"boolean"==typeof e?"boolean":Array.isArray(e)?"array":"object"==typeof e?"object":"unknown"}setAuthToken(e,t){this.accessToken=e,this.projectId=t}clearAuth(){this.accessToken=void 0,this.projectId=void 0}setConfiguration(e,t,n){void 0!==e&&(this.placeholderEndpoint=e),void 0!==t&&(this.requestContentType=t),void 0!==n&&(this.responseAcceptHeader=n)}convertPayloadToProtobuf(e){const t={};for(const[n,o]of Object.entries(e.content.fields))if(o&&"object"==typeof o&&"value"in o){const e=o;let r=e.type;r||(console.warn(`Field '${n}' missing type in protobuf conversion, inferring from value`),r=this.inferSanityType(e.value)),t[n]={value:"string"==typeof e.value?e.value:JSON.stringify(e.value),dnt:e.dnt||!1,type:r,path:e.path??n}}else console.warn(`Field '${n}' not in TranslatableField format, wrapping with inferred type`),t[n]={value:"string"==typeof o?o:JSON.stringify(o),dnt:!1,type:this.inferSanityType(o),path:n};const n=translation_request.TranslationRequestPayload.create({content:{body:e.content.body,title:e.content.title,slug:e.content.slug,fields:t},project:this.projectId||"",format:e.format,metadata:{documentId:e.metadata.documentId,documentType:e.metadata.documentType,title:e.metadata.title,sourceLanguage:e.metadata.sourceLanguage||"",targetLanguage:e.metadata.targetLanguage||"",targetLocales:e.metadata.targetLocales||[]}});return translation_request.TranslationRequestPayload.encode(n).finish()}convertPayloadToProtobufJSON(e){const t={};for(const[n,o]of Object.entries(e.content.fields))if(o&&"object"==typeof o&&"value"in o){const e=o;t[n]={value:"string"==typeof e.value?e.value:JSON.stringify(e.value),dnt:e.dnt||!1,type:e.type||"unknown",path:e.path??n}}else t[n]={value:"string"==typeof o?o:JSON.stringify(o),dnt:!1,type:"unknown",path:n};const n=translation_request.TranslationRequestPayload.create({content:{body:e.content.body,title:e.content.title,slug:e.content.slug,fields:t},project:this.projectId||"",format:e.format,metadata:{documentId:e.metadata.documentId,documentType:e.metadata.documentType,title:e.metadata.title,sourceLanguage:e.metadata.sourceLanguage||"",targetLanguage:e.metadata.targetLanguage||"",targetLocales:e.metadata.targetLocales||[]}});return translation_request.TranslationRequestPayload.toJSON(n)}normalizeTranslatedFields(e){const t={};if(!e||"object"!=typeof e)return t;for(const[n,o]of Object.entries(e))t[n]=o&&"object"==typeof o&&"value"in o?{value:o.value,dnt:o.dnt||!1,type:o.type||this.inferSanityType(o.value)}:{value:o,dnt:!1,type:this.inferSanityType(o)};return t}convertProtobufBinaryToResponse(e){const t=translation_response.TranslationResponse.decode(e),n=t.translatedDocuments.map(e=>{const t={};if(e.fields&&"object"==typeof e.fields)for(const[n,o]of Object.entries(e.fields))if(o&&"object"==typeof o&&"value"in o){const e=o.value,r=o.type;try{const s=JSON.parse(e);t[n]={value:s,dnt:o.dnt||!1,type:r||this.inferSanityType(s)}}catch{t[n]={value:e,dnt:o.dnt||!1,type:r||this.inferSanityType(e)}}}return{body:e.body,title:e.title,slug:e.slug,fields:t,locale:e.locale}});return{success:t.success,translatedDocuments:n,sourceLocale:t.sourceLocale,error:t.error,requestId:t.requestId}}convertProtobufJSONToResponse(e){const t=translation_response.TranslationResponse.fromJSON(e),n=t.translatedDocuments.map((t,n)=>{const o=e.translatedDocuments?.[n],r={};if(t.fields&&"object"==typeof t.fields)for(const[e,n]of Object.entries(t.fields)){const t=o?.fields?.[e];if(n&&"object"==typeof n&&"value"in n){const o=n.value,s=n.type;if(""!==o&&void 0!==o||void 0===t||""===t)try{const t=JSON.parse(o);r[e]={value:t,dnt:n.dnt||!1,type:s||this.inferSanityType(t)}}catch{r[e]={value:o,dnt:n.dnt||!1,type:s||this.inferSanityType(o)}}else r[e]=t}else r[e]=void 0===t||n&&""!==n?n:t}if(o?.fields&&"object"==typeof o.fields)for(const[e,t]of Object.entries(o.fields))e in r||(r[e]=t);const s=this.normalizeTranslatedFields(r);return{body:t.body,title:t.title,slug:t.slug,fields:s,locale:t.locale}});return{success:t.success,translatedDocuments:n,sourceLocale:t.sourceLocale,error:t.error,requestId:t.requestId}}prepareTranslationRequest(e,t="document",n,o,r){if(!e||!e.documentId||!e.htmlContent)throw new Error("Invalid document content provided");const s={};if(e.fields)for(const[t,n]of Object.entries(e.fields))if(n&&"object"==typeof n&&"value"in n){const e=n;e.type||console.warn(`Field '${t}' missing type, inferring from value`),s[t]={...e,type:e.type||this.inferSanityType(e.value)}}else console.warn(`Field '${t}' not in TranslatableField format, converting`),s[t]={value:n,dnt:!1,type:this.inferSanityType(n)};console.log("[TranslationService] prepareTranslationRequest - titleFoundAtTopLevel:",{fromContent:e.titleFoundAtTopLevel,willUse:e.titleFoundAtTopLevel??!0});const a={content:{body:e.htmlContent,title:e.title||`Document ${e.documentId}`,slug:e.slug||"",fields:s},format:"html",metadata:{documentId:e.documentId,documentType:t,title:e.title||`Document ${e.documentId}`,...n&&{sourceLanguage:n},...o&&{targetLanguage:o},...r&&r.length>0&&{targetLocales:r},titleFoundAtTopLevel:e.titleFoundAtTopLevel??!0}};return{documentId:e.documentId,endpoint:this.placeholderEndpoint,payload:a}}async translateDocument(e,t="document",n,o,r){const s=this.prepareTranslationRequest(e,t,n,o,r);return this.sendTranslationRequest(s)}async sendTranslationRequest(e){try{this.logTranslationRequest(e);const t={"Content-Type":this.requestContentType,Accept:this.responseAcceptHeader};let n;if(this.accessToken&&(t.Authorization=`Bearer ${this.accessToken}`),"application/x-protobuf"===this.requestContentType)n=this.convertPayloadToProtobuf(e.payload);else{const t=this.convertPayloadToProtobufJSON(e.payload);n=JSON.stringify(t)}const o=await fetch(e.endpoint,{method:"POST",headers:t,body:n});if(!o.ok){if(401===o.status)return{success:!1,error:"Authentication failed. Please check your access token in the Easyling Configuration."};throw new Error(`HTTP error! status: ${o.status}`)}if("application/x-protobuf"===this.responseAcceptHeader){const e=await o.arrayBuffer(),t=new Uint8Array(e);return this.convertProtobufBinaryToResponse(t)}const r=await o.json();try{if(void 0!==r.success&&(r.translatedDocuments||r.error))return this.convertProtobufJSONToResponse(r)}catch(e){console.warn("Failed to parse response as protobuf format, falling back to legacy handling:",e)}if(r.translatedDocuments&&Array.isArray(r.translatedDocuments))return{success:!0,translatedDocuments:r.translatedDocuments.map(e=>({...e,fields:this.normalizeTranslatedFields(e.fields||{})})),sourceLocale:r.sourceLocale,requestId:r.requestId};if(r.translations){const e=[];for(const[t,n]of Object.entries(r.translations))if(n&&"object"==typeof n&&"content"in n){const o=n.content;e.push({...o,fields:this.normalizeTranslatedFields(o.fields||{}),locale:t})}return{success:!0,translatedDocuments:e,sourceLocale:r.sourceLocale,requestId:r.requestId,translations:r.translations}}if(r.translatedContent){const t=e.payload.metadata.targetLanguage||e.payload.metadata.targetLocales?.[0];return{success:!0,translatedDocuments:[{...r.translatedContent,fields:this.normalizeTranslatedFields(r.translatedContent.fields||{}),locale:t}],sourceLocale:e.payload.metadata.sourceLanguage,requestId:r.requestId,translatedContent:r.translatedContent}}if(r.content){const t=e.payload.metadata.targetLanguage||e.payload.metadata.targetLocales?.[0];return{success:!0,translatedDocuments:[{...r.content,fields:this.normalizeTranslatedFields(r.content.fields||{}),locale:t}],sourceLocale:e.payload.metadata.sourceLanguage,requestId:r.requestId,translatedContent:r.content}}throw new Error("Invalid response format: missing translatedDocuments, translations, or translatedContent")}catch(t){return console.error(`Translation request failed for document ${e.documentId}:`,t),{success:!1,error:t instanceof Error?t.message:"Unknown error occurred"}}}logTranslationRequest(e){console.log("Translation Request:",{timestamp:(new Date).toISOString(),documentId:e.documentId,endpoint:e.endpoint,payload:e.payload})}async processBulkTranslation(e,t="document",n,o,r){const s={totalDocuments:e.length,processedDocuments:0,failedDocuments:0,requests:[],responses:[]},a=r?.length||1;console.log(`Starting bulk translation for ${e.length} documents to ${a} locale(s)`);for(const a of e)try{const e=this.prepareTranslationRequest(a,t,n,o,r),i=await this.sendTranslationRequest(e);s.requests.push(e),s.responses.push(i),i.success?s.processedDocuments++:s.failedDocuments++}catch(e){console.error(`Failed to process document ${a.documentId}:`,e),s.failedDocuments++,s.responses.push({success:!1,error:e instanceof Error?e.message:"Unknown error occurred"})}return this.logBulkTranslationSummary(s),s}logBulkTranslationSummary(e){console.log("Bulk Translation Summary:",{timestamp:(new Date).toISOString(),totalDocuments:e.totalDocuments,processedDocuments:e.processedDocuments,failedDocuments:e.failedDocuments,successRate:e.totalDocuments>0?(e.processedDocuments/e.totalDocuments*100).toFixed(2)+"%":"0%"})}setEndpoint(e){this.placeholderEndpoint=e}getEndpoint(){return this.placeholderEndpoint}}class CollisionDetectionError extends Error{constructor(e,t,n){super(e),this.code=t,this.details=n,this.name="CollisionDetectionError"}}class CollisionDetectionService{constructor(e){this.client=e}async detectCollision(e){const{sourceDocumentId:t,targetLocale:n,slug:o,documentType:r}=e;if(!t||!n)throw new CollisionDetectionError("sourceDocumentId and targetLocale are required","INVALID_OPTIONS");const s=t.replace(/^drafts\./,"");try{const e=await this.findByParentReference(s,n,r);if(e)return console.log(`[CollisionDetection] Found collision by parent reference: ${e._id}`),{detected:!0,existingDocument:e,matchedBy:"parent"};if(o){const e=await this.findBySlugAndLocale(o,n,r);if(e)return console.log(`[CollisionDetection] Found collision by slug-locale: ${e._id}`),{detected:!0,existingDocument:e,matchedBy:"slug-locale"}}return console.log(`[CollisionDetection] No collision detected for source ${s}, locale ${n}`),{detected:!1}}catch(e){throw console.error("[CollisionDetection] Error during collision detection:",e),new CollisionDetectionError("Failed to detect collision","DETECTION_FAILED",e)}}async findByParentReference(e,t,n){const o=n?"&& _type == $documentType":"",r=`*[\n (\n parentDocument._ref == $sourceId ||\n parentDocument._ref == $sourceIdWithDrafts\n ) &&\n (\n locale == $targetLocale ||\n locale.value == $targetLocale\n )\n ${o}\n ][0]`,s=`*[\n (\n parentDocument._ref == $sourceId ||\n parentDocument._ref == $sourceIdWithDrafts\n ) &&\n _id match $idPattern\n ${o}\n ][0]`,a={sourceId:e,sourceIdWithDrafts:`drafts.${e}`,targetLocale:t,idPattern:`*-${t}-*`};n&&(a.documentType=n);let i=await this.client.fetch(r,a);return i||(i=await this.client.fetch(s,a)),i||null}async findBySlugAndLocale(e,t,n){const o=n?"&& _type == $documentType":"",r=`*[\n (\n slug == $slug ||\n slug.current == $slug\n ) &&\n (\n locale == $targetLocale ||\n locale.value == $targetLocale\n )\n ${o}\n ][0]`,s=`*[\n (\n slug == $slug ||\n slug.current == $slug\n ) &&\n _id match $idPattern\n ${o}\n ][0]`,a={slug:e,targetLocale:t,idPattern:`*-${t}-*`};n&&(a.documentType=n);let i=await this.client.fetch(r,a);return i||(i=await this.client.fetch(s,a)),i||null}async detectBulkCollisions(e,t,n,o){const r=new Map;for(const s of t)try{const t=await this.detectCollision({sourceDocumentId:e,targetLocale:s,slug:n,documentType:o});r.set(s,t)}catch(e){console.error(`[CollisionDetection] Error checking locale ${s}:`,e),r.set(s,{detected:!1})}return r}}class DocumentCreationService{constructor(e,t){this.defaultCreationMode="draft",this.collisionDetectionService=null,this.defaultCollisionResolutionMode="replace",this.defaultExistingDocumentHandling="draft",this.client=e,t&&(this.defaultCreationMode=t),this.collisionDetectionService=new CollisionDetectionService(e)}setDefaultCreationMode(e){this.defaultCreationMode=e}setDefaultCollisionResolutionMode(e){this.defaultCollisionResolutionMode=e}setDefaultExistingDocumentHandling(e){this.defaultExistingDocumentHandling=e}setCollisionResolutionConfig(e,t){this.defaultCollisionResolutionMode=e,t&&(this.defaultExistingDocumentHandling=t)}async replaceExistingDocument(e,t,n){try{const o=e._id,r=o.startsWith("drafts."),s={...t,_id:o,_createdAt:e._createdAt};delete s._rev,delete s._updatedAt,console.log(`[ReplaceDocument] Replacing document ${o}`);const a=await this.client.createOrReplace(s);if(console.log(`[ReplaceDocument] Successfully replaced document ${a._id}`),"draft"===n&&!r){const e=`drafts.${o}`,t=await this.client.createOrReplace({...s,_id:e});return{success:!0,documentId:t._id,document:t}}if("published"===n&&r){const e=o.replace(/^drafts\./,""),t=await this.client.createOrReplace({...s,_id:e});return{success:!0,documentId:t._id,document:t}}return{success:!0,documentId:a._id,document:a}}catch(e){return console.error("[ReplaceDocument] Failed to replace document:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error during document replacement"}}}async handleExistingDocument(e,t){try{const n=e._id;if("delete"===t){if(console.log(`[HandleExistingDocument] Deleting document ${n}`),await this.client.delete(n),!n.startsWith("drafts."))try{await this.client.delete(`drafts.${n}`)}catch{}return console.log(`[HandleExistingDocument] Successfully deleted document ${n}`),{success:!0}}if("draft"===t){if(console.log(`[HandleExistingDocument] Setting document ${n} to draft state`),n.startsWith("drafts."))return console.log(`[HandleExistingDocument] Document ${n} is already a draft`),{success:!0};const t=`drafts.${n}`;return await this.client.createOrReplace({...e,_id:t,_rev:void 0,_createdAt:void 0,_updatedAt:void 0}),await this.client.delete(n),console.log(`[HandleExistingDocument] Successfully set document to draft: ${t}`),{success:!0}}return{success:!0}}catch(e){return console.error("[HandleExistingDocument] Failed to handle existing document:",e),{success:!1,error:e instanceof Error?e.message:"Unknown error during existing document handling"}}}async createDocumentFromTranslation(e,t,n={}){try{const o=this.validateInputsForDocumentCreation(e,t,n);if(!o.isValid)return{success:!1,error:`Input validation failed: ${o.errors.join(", ")}`};const r=t.translatedDocuments?.[0]||t.translatedContent;if(console.log("[DocumentCreation] createDocumentFromTranslation:",{titleFoundAtTopLevelFromOptions:n.titleFoundAtTopLevel,translatedContentKeys:r?Object.keys(r):[]}),!t.success||!r)return{success:!1,error:"Translation response does not contain valid translated content"};const s=this.validateTranslationResponseForCreation(t);if(!s.isValid)return{success:!1,error:`Translation response validation failed: ${s.errors.join(", ")}`};const a=await this.mergeTranslatedContent(e,r,n),i=this.validateDocumentStructure(a);if(!i.isValid)return{success:!1,error:`Document validation failed: ${i.errors.join(", ")}`};const l=this.validateBusinessRules(a,e);if(!l.isValid)return{success:!1,error:`Business rule validation failed: ${l.errors.join(", ")}`};let c;if(l.slugNeedsFallback){const t=n.targetLanguage||"translated",o="object"==typeof e.slug?e.slug.current:e.slug,r=`${o}_${t}`;"object"==typeof a.slug&&null!==a.slug&&"_type"in a.slug?a.slug={_type:"slug",current:r}:a.slug=r,c={documentId:a._id,originalSlug:o,fallbackSlug:r,locale:t,reason:"Translation did not produce a different slug - locale suffix applied"},console.log(`[Slug Fallback Applied] Document ${a._id}: "${o}" → "${r}"`)}const u=n.creationMode||this.defaultCreationMode,d=n.collisionResolutionMode||this.defaultCollisionResolutionMode,f=n.existingDocumentHandling||this.defaultExistingDocumentHandling;let p,h=null;if(this.collisionDetectionService&&n.targetLanguage&&n.parentDocumentId){const t="object"==typeof a.slug&&null!==a.slug&&"current"in a.slug?a.slug.current:"string"==typeof a.slug?a.slug:void 0;if(h=await this.collisionDetectionService.detectCollision({sourceDocumentId:n.parentDocumentId,targetLocale:n.targetLanguage,slug:t,documentType:e._type}),h.detected){if(console.log(`[CollisionHandling] Collision detected for source ${n.parentDocumentId}, locale ${n.targetLanguage}`),console.log(`[CollisionHandling] Resolution mode: ${d}, Existing doc handling: ${f}`),p={collisionDetected:!0,matchedBy:h.matchedBy,existingDocumentId:h.existingDocument?._id},"replace"===d&&h.existingDocument){const e=await this.replaceExistingDocument(h.existingDocument,a,u);return e.success?(p.resolutionAction="replaced",p.existingDocumentAction="none",{success:!0,documentId:e.documentId,document:e.document,slugFallback:c,collisionInfo:p}):{success:!1,error:`Failed to replace existing document: ${e.error}`,collisionInfo:p}}if("create"===d&&h.existingDocument){const e=await this.handleExistingDocument(h.existingDocument,f);p.resolutionAction="created_new",p.existingDocumentAction="draft"===f?"set_to_draft":"deleted",e.success||console.warn(`[CollisionHandling] Failed to handle existing document: ${e.error}`)}}else p={collisionDetected:!1,resolutionAction:"none"}}try{let e;if("draft"===u){const t=a._id.startsWith("drafts.")?a._id:`drafts.${a._id}`;console.log("Creating draft document in Sanity:",t),e=await this.client.create({...a,_id:t}),console.log("Draft document created successfully:",e._id)}else{const t=a._id.startsWith("drafts.")?a._id.replace(/^drafts\./,""):a._id;console.log("Creating published document in Sanity:",t),e=await this.client.create({...a,_id:t}),console.log("Published document created successfully:",e._id)}return{success:!0,documentId:e._id,document:e,slugFallback:c,collisionInfo:p}}catch(e){return console.error("Failed to create document in Sanity:",e),{success:!1,error:`Failed to save document to Sanity: ${e instanceof Error?e.message:"Unknown Sanity error"}`}}}catch(t){return{success:!1,error:this.formatErrorMessage(t,e._id)}}}validateInputsForDocumentCreation(e,t,n){const o=[];return e?(e._id||o.push("Original document must have an _id"),e._type||o.push("Original document must have a _type"),t?(n.targetLanguage&&"string"!=typeof n.targetLanguage&&o.push("Target language must be a string"),n.sourceLanguage&&"string"!=typeof n.sourceLanguage&&o.push("Source language must be a string"),void 0!==n.createAsVariant&&"boolean"!=typeof n.createAsVariant&&o.push("createAsVariant must be a boolean"),n.parentDocumentId&&"string"!=typeof n.parentDocumentId&&o.push("parentDocumentId must be a string"),{isValid:0===o.length,errors:o}):(o.push("Translation response is required"),{isValid:!1,errors:o})):(o.push("Original document is required"),{isValid:!1,errors:o})}validateBusinessRules(e,t){const n=[];let o=!1;if(e._id===t._id&&n.push("New document ID must be different from original document ID"),e._type!==t._type&&n.push(`New document type (${e._type}) must match original document type (${t._type})`),this.documentHasContent(e)||n.push("New document must contain some translatable content"),e.slug&&t.slug){const n="object"==typeof e.slug?e.slug.current:e.slug;n===("object"==typeof t.slug?t.slug.current:t.slug)&&(console.warn(`[Slug Fallback] Document ${e._id}: Slug "${n}" is same as original. Will apply locale suffix.`),o=!0)}return{isValid:0===n.length,errors:n,slugNeedsFallback:o}}documentHasContent(e){const t=["title","name","heading","label"],n=["body","content"];for(const n of t)if(e[n]&&"string"==typeof e[n]&&e[n].trim().length>0)return!0;for(const t of n)if(e[t]){if("string"==typeof e[t]&&e[t].trim().length>0)return!0;if(Array.isArray(e[t])&&e[t].length>0)return!0}return!!this.hasContentInNestedFields(e,t,n)}hasContentInNestedFields(e,t,n){for(const[o,r]of Object.entries(e))if(!o.startsWith("_")&&null!=r){if("object"==typeof r&&!Array.isArray(r)){for(const e of t)if(r[e]&&"string"==typeof r[e]&&r[e].trim().length>0)return!0;for(const e of n)if(r[e]){if("string"==typeof r[e]&&r[e].trim().length>0)return!0;if(Array.isArray(r[e])&&r[e].length>0)return!0}if(this.hasContentInNestedFields(r,t,n))return!0}if(Array.isArray(r))for(const e of r)if(e&&"object"==typeof e){for(const n of t)if(e[n]&&"string"==typeof e[n]&&e[n].trim().length>0)return!0;for(const t of n)if(e[t]){if("string"==typeof e[t]&&e[t].trim().length>0)return!0;if(Array.isArray(e[t])&&e[t].length>0)return!0}if(this.hasContentInNestedFields(e,t,n))return!0}}return!1}formatErrorMessage(e,t){const n=e instanceof Error?e.message:"Unknown error occurred during document creation",o=t?` (Document ID: ${t})`:"";if(e instanceof Error){if(e.message.includes("validation"))return`Document validation error${o}: ${e.message}`;if(e.message.includes("network")||e.message.includes("fetch"))return`Network error during document creation${o}: ${e.message}`;if(e.message.includes("permission")||e.message.includes("unauthorized"))return`Permission error during document creation${o}: ${e.message}`}return`Document creation error${o}: ${n}`}async createBulkDocumentsFromTranslations(e,t,n={}){const o={totalDocuments:e.length,successfulCreations:0,failedCreations:0,results:[],errors:[],rollbackInfo:{canRollback:!0,createdDocumentIds:[],rollbackInstructions:[]},slugFallbacks:[]},r=this.validateBulkTranslationResponses(e,t);if(r.length>0){o.errors.push(...r),o.failedCreations=e.length,o.rollbackInfo.canRollback=!1,o.rollbackInfo.rollbackInstructions.push("No documents were created due to validation failures");for(let t=0;t<e.length;t++)o.results.push({success:!1,error:"Bulk validation failed - no documents created"});return o}const s=[];for(let r=0;r<e.length;r++){const a=e[r],i=t[r];if(!i){const e=`No translation response found for document ${a._id}`;o.results.push({success:!1,error:e}),o.errors.push(e),o.failedCreations++;continue}try{const e=this.validateTranslationResponseForCreation(i);if(!e.isValid){const t=`Pre-creation validation failed for ${a._id}: ${e.errors.join(", ")}`;o.results.push({success:!1,error:t}),o.errors.push(t),o.failedCreations++;continue}const t=i.translatedDocuments||(i.translatedContent?[i.translatedContent]:[]);if(0===t.length){const e=`No translated documents found in response for ${a._id}`;o.results.push({success:!1,error:e}),o.errors.push(e),o.failedCreations++;continue}for(let e=0;e<t.length;e++){const r=t[e],l=r.locale||n.targetLanguage||"translated";console.log(`Creating document for ${a._id} with target locale: ${l}`);const c={...i,translatedDocuments:[r],translatedContent:r},u=await this.createDocumentFromTranslation(a,c,{...n,targetLanguage:l});o.results.push(u),u.success&&u.documentId?(o.successfulCreations++,s.push({documentId:u.documentId,originalId:a._id}),o.rollbackInfo.createdDocumentIds.push(u.documentId),u.slugFallback&&o.slugFallbacks.push(u.slugFallback)):(o.failedCreations++,u.error&&o.errors.push(u.error))}}catch(e){const t=e instanceof Error?e.message:"Unknown error occurred";o.results.push({success:!1,error:t}),o.errors.push(t),o.failedCreations++}}return o.successfulCreations>0?o.rollbackInfo.rollbackInstructions=[`${o.successfulCreations} documents were successfully created.`,"To rollback these changes, you would need to delete the following document IDs:",...o.rollbackInfo.createdDocumentIds.map(e=>`- ${e}`),"Note: This plugin does not automatically delete documents for safety reasons.","Manual deletion through Sanity Studio or API calls would be required."]:o.rollbackInfo.rollbackInstructions=["No documents were created, no rollback needed."],o.slugFallbacks.length>0&&(console.log(`[Slug Fallback Summary] ${o.slugFallbacks.length} document(s) had slug fallback applied:`),o.slugFallbacks.forEach(e=>{console.log(` - ${e.documentId}: "${e.originalSlug}" → "${e.fallbackSlug}" (locale: ${e.locale})`)})),o}validateBulkTranslationResponses(e,t){const n=[];if(e.length!==t.length)return n.push(`Mismatch between original documents (${e.length}) and translation responses (${t.length})`),n;for(let o=0;o<e.length;o++){const r=e[o],s=t[o];r?r._id?r._type?s?s.success&&(0!==(s.translatedDocuments||(s.translatedContent?[s.translatedContent]:[])).length||n.push(`Translation response at index ${o} missing translatedDocuments/translatedContent despite success=true`)):n.push(`Translation response at index ${o} is null or undefined`):n.push(`Original document at index ${o} missing _type`):n.push(`Original document at index ${o} missing _id`):n.push(`Original document at index ${o} is null or undefined`)}return n}validateTranslationResponseForCreation(e){const t=[];if(!e.success)return t.push("Translation response indicates failure"),{isValid:!1,errors:t};const n=e.translatedDocuments||(e.translatedContent?[e.translatedContent]:[]);if(0===n.length)return t.push("Translation response missing translatedDocuments/translatedContent"),{isValid:!1,errors:t};for(let e=0;e<n.length;e++){const o=n[e];"object"==typeof o&&null!==o?(o.body||o.title||o.fields||t.push(`Translated document at index ${e} must contain at least one of: body, title, or fields`),void 0!==o.body&&("string"!=typeof o.body?t.push(`Translated document at index ${e} body must be a string`):0===o.body.trim().length&&t.push(`Translated document at index ${e} body cannot be empty`)),void 0!==o.title&&("string"!=typeof o.title?t.push(`Translated document at index ${e} title must be a string`):0===o.title.trim().length&&t.push(`Translated document at index ${e} title cannot be empty`)),void 0!==o.slug&&("string"!=typeof o.slug?t.push(`Translated document at index ${e} slug must be a string`):0===o.slug.trim().length?t.push(`Translated document at index ${e} slug cannot be empty`):/^[a-z0-9-_]+$/.test(o.slug)||t.push(`Translated document at index ${e} slug must contain only lowercase letters, numbers, hyphens, and underscores`)),void 0!==o.fields&&("object"!=typeof o.fields||null===o.fields||Array.isArray(o.fields))&&t.push(`Translated document at index ${e} fields must be an object`)):t.push(`Translated document at index ${e} must be an object`)}return{isValid:0===t.length,errors:t}}createRollbackPlan(e){return 0===e.length?{canRollback:!0,createdDocumentIds:[],rollbackInstructions:["No documents were created, no rollback needed."]}:{canRollback:!0,createdDocumentIds:[...e],rollbackInstructions:[`Rollback plan for ${e.length} created documents:`,"","1. Manual deletion required (for safety):",...e.map(e=>` - Delete document: ${e}`),"","2. Alternative: Use Sanity CLI or API:"," sanity documents delete <document-id>","","3. Or via Sanity Client API:"," client.delete(documentId)","","WARNING: This plugin does not provide automatic rollback to prevent","accidental data loss. Please review each document before deletion."]}}parseFieldPath(e){const t=[],n=e.match(/^\*\[.*?\]\[0\]\./),o=n?e.substring(n[0].length):e,r=/([^.[]+)(?:\[_key\s*==\s*"([^"]+)"\])?/g;let s;for(;null!==(s=r.exec(o));){const[,e,n]=s;n?t.push({type:"arrayKey",name:e,key:n}):t.push({type:"property",name:e}),"."===o[r.lastIndex]&&r.lastIndex++}return t}unflattenFields(e,t){const n={};for(const[o,r]of Object.entries(e)){const e=r&&"object"==typeof r&&"path"in r?r.path:o,s=this.parseFieldPath(e);if(0===s.length)continue;let a,i=r;if(r&&"object"==typeof r&&"value"in r){if(i=r.value,a=r.type,"string"==typeof i&&(i.startsWith("[")&&i.endsWith("]")||i.startsWith("{")&&i.endsWith("}")))try{i=JSON.parse(i)}catch{}"block"===a&&"string"==typeof i&&this.isHtmlContent(i)&&(i=this.convertHtmlToPortableText(i))}let l=n,c=t;for(let e=0;e<s.length;e++){const t=s[e],n=e===s.length-1;if("arrayKey"===t.type){t.name in l||(c&&Array.isArray(c[t.name])?l[t.name]=JSON.parse(JSON.stringify(c[t.name])):l[t.name]=[]);const e=l[t.name];let o=e.find(e=>e._key===t.key);if(!o){let n=null;c&&Array.isArray(c[t.name])&&(n=c[t.name].find(e=>e._key===t.key)),o=n?JSON.parse(JSON.stringify(n)):{_key:t.key},e.push(o)}n?Object.assign(o,i):(l=o,c=c?.[t.name]?.find(e=>e._key===t.key))}else n?l[t.name]=i:(t.name in l||(c&&"object"==typeof c[t.name]&&null!==c[t.name]?l[t.name]=Array.isArray(c[t.name])?JSON.parse(JSON.stringify(c[t.name])):{...c[t.name]}:l[t.name]={}),l=l[t.name],c=c?.[t.name])}}return n}getOriginalValueByPath(e,t){const n=t.split(".");let o=e;for(const e of n){if(null==o||"object"!=typeof o)return;o=o[e]}return o}async mergeTranslatedContent(e,t,n){const o=n.targetLanguage||t.locale,r={...e,_id:this.generateNewDocumentId(e._id,o),_rev:void 0,_createdAt:void 0,_updatedAt:void 0},s=!1!==n.titleFoundAtTopLevel;console.log("[DocumentCreation] Title handling:",{originalDocumentTitle:e.title,originalDocumentHasTitle:"title"in e,translatedContentTitle:t.title,titleFoundAtTopLevelFromOptions:n.titleFoundAtTopLevel,shouldWriteTopLevelTitle:s,newDocumentTitleBefore:r.title}),t.title&&t.title.trim()&&s?(r.title=t.title,console.log("[DocumentCreation] Writing title to top level:",t.title)):!s&&"title"in r?(console.log("[DocumentCreation] Removing inherited top-level title field"),delete r.title):console.log("[DocumentCreation] NOT writing title. Reason:",{hasTitle:!!t.title,titleNotEmpty:!!t.title?.trim(),shouldWriteTopLevelTitle:s}),t.slug&&t.slug.trim()&&("object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug?r.slug={_type:"slug",current:t.slug}:r.slug=t.slug);const a=!1!==n.bodyFoundAtTopLevel;if(console.log("[DocumentCreation] Body handling:",{hasTranslatedBody:!!t.body,bodyFoundAtTopLevelFromOptions:n.bodyFoundAtTopLevel,bodyFieldNameFromOptions:n.bodyFieldName,shouldWriteTopLevelBody:a,originalHasBody:"body"in e,originalHasContent:"content"in e}),t.body&&t.body.trim()){const o=this.convertHtmlToPortableText(t.body);if(a){const t=["body","content","text","description"];let n=!1;for(const s of t)if(e[s]){r[s]=o,console.log("[DocumentCreation] Writing body to top-level field:",s),n=!0;break}n||(r.body=o,console.log('[DocumentCreation] Writing body to new top-level "body" field'))}else{console.log("[DocumentCreation] NOT writing body to top level (was found in nested field:",n.bodyFieldName,")");const t=["body","content","text","description"];for(const n of t)n in r&&!(n in e)&&(console.log("[DocumentCreation] Removing inherited top-level field:",n),delete r[n])}}if(t.fields&&"object"==typeof t.fields){const n=this.unflattenFields(t.fields,e);for(const[t,o]of Object.entries(n)){if("title"===t||"slug"===t||void 0===o)continue;const n=this.processTranslatedField(t,o,e[t]);void 0!==n&&(r[t]=n)}for(const[o,s]of Object.entries(t.fields))if("title"!==o&&"slug"!==o&&void 0!==s&&o.includes(".")&&!(o.split(".")[0]in n)){const t=this.getOriginalValueByPath(e,o),n=this.processTranslatedField(o,s,t);if(void 0!==n){const e=o.split(".");let t=r;for(let n=0;n<e.length-1;n++){const o=e[n];o in t&&null!==t[o]&&"object"==typeof t[o]||(t[o]={}),t=t[o]}t[e[e.length-1]]=n}}}o&&(e.locale&&"object"==typeof e.locale&&"value"in e.locale?r.locale={...e.locale,value:o}:r.locale&&"object"==typeof r.locale&&"value"in r.locale?r.locale={...r.locale,value:o}:r.locale=o);const i=Object.keys(r);for(const e of i)null===r[e]&&delete r[e];return n.createAsVariant&&n.parentDocumentId&&(r.parentDocument={_type:"reference",_ref:n.parentDocumentId}),r}processTranslatedField(e,t,n){if(null==t)return t;let o=t,r=!1;if(t&&"object"==typeof t&&"value"in t&&(o=t.value,r=t.dnt||!1),r&&void 0!==n)return n;if(n&&"object"==typeof n&&null!==n){if("dnt"in n&&"value"in n){let e=o;return t&&"object"==typeof t&&"value"in t&&(e=t.value),null!=e&&""!==e||null===n.value||void 0===n.value||""===n.value?{dnt:r,value:e}:n}if("_type"in n&&"slug"===n._type)return{_type:"slug",current:"string"==typeof o?o:String(o)};if("_type"in n&&("date"===n._type||"datetime"===n._type))return{_type:n._type,value:o};if("_type"in n&&"reference"===n._type)return n}return"string"==typeof o&&this.isHtmlContent(o)?this.convertHtmlToPortableText(o):o}convertHtmlToPortableText(e){if(!e||!e.trim())return[];const t=[],n=/<(h[1-6]|p|div|blockquote|li)([^>]*)>(.*?)<\/\1>/gi;let o,r=0;for(;null!==(o=n.exec(e));){const[,e,,n]=o;if(!n.trim())continue;const s={_type:"block",_key:this.generateBlockKey(),style:this.getBlockStyle(e.toLowerCase()),children:this.parseInlineContent(n),markDefs:[]};"li"===e.toLowerCase()&&(s.listItem="bullet"),t.push(s),r=o.index+o[0].length}const s=e.substring(r).trim();if(s){const e=s.replace(/<[^>]+>/g,"").trim();e&&t.push({_type:"block",_key:this.generateBlockKey(),style:"normal",children:this.parseInlineContent(e),markDefs:[]})}if(0===t.length&&e.trim()){const n=e.replace(/<[^>]+>/g,"").trim();n&&t.push({_type:"block",_key:this.generateBlockKey(),style:"normal",children:this.parseInlineContent(n),markDefs:[]})}return t}parseInlineContent(e){const t=[],n=e.replace(/<strong[^>]*>(.*?)<\/strong>/gi,"**$1**").replace(/<em[^>]*>(.*?)<\/em>/gi,"*$1*").replace(/<u[^>]*>(.*?)<\/u>/gi,"_$1_").replace(/<code[^>]*>(.*?)<\/code>/gi,"`$1`").replace(/<[^>]+>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'");return n.trim()&&t.push({_type:"span",_key:this.generateSpanKey(),text:n,marks:[]}),t}getBlockStyle(e){return{h1:"h1",h2:"h2",h3:"h3",h4:"h4",h5:"h5",h6:"h6",blockquote:"blockquote",p:"normal",div:"normal",li:"normal"}[e]||"normal"}isHtmlContent(e){return/<[^>]+>/.test(e)}generateNewDocumentId(e,t){return`${e.startsWith("drafts.")?e.replace(/^drafts\./,""):e}${t?`-${t}`:"-translated"}-${Date.now()}`}generateBlockKey(){return Math.random().toString(36).substr(2,9)}generateSpanKey(){return Math.random().toString(36).substr(2,9)}validateDocumentStructure(e){const t=[];e._id||t.push("Document must have an _id"),e._type||t.push("Document must have a _type");const n=["body","content","text","description"];for(const o of n)if(e[o]&&Array.isArray(e[o])){const n=this.validatePortableTextArray(e[o],o);n.isValid||t.push(...n.errors)}if(e.slug&&"object"==typeof e.slug&&null!==e.slug&&"_type"in e.slug){const n=e.slug;"slug"!==n._type&&t.push('Slug object must have _type of "slug"'),n.current||t.push("Slug object must have a current value")}return{isValid:0===t.length,errors:t}}validatePortableTextArray(e,t){const n=[];if(!Array.isArray(e))return n.push(`${t} must be an array`),{isValid:!1,errors:n};for(let o=0;o<e.length;o++){const r=e[o];if(!r||"object"!=typeof r){n.push(`${t}[${o}] must be an object`);continue}const s=r;if(s._type||n.push(`${t}[${o}] must have a _type`),s._key||n.push(`${t}[${o}] must have a _key`),"block"===s._type)if(Array.isArray(s.children)){const e=s.children;for(let r=0;r<e.length;r++){const s=e[r];if(!s||"object"!=typeof s){n.push(`${t}[${o}].children[${r}] must be an object`);continue}const a=s;a._type||n.push(`${t}[${o}].children[${r}] must have a _type`),a._key||n.push(`${t}[${o}].children[${r}] must have a _key`)}}else n.push(`${t}[${o}] block must have children array`)}return{isValid:0===n.length,errors:n}}}const UNIFIED_CONFIG_DOC_ID="sanity-translation-plugin.config",UNIFIED_CONFIG_DOC_TYPE="EL_PluginConfiguration";class UnifiedConfigStorage{constructor(e){this.client=e}convertDNTArrayToMap(e){if(!e||!Array.isArray(e))return{};const t={};for(const n of e)if(n.documentType&&n.fields){t[n.documentType]={};for(const e of n.fields)e.fieldPath&&(t[n.documentType][e.fieldPath]=!1!==e.dnt)}return t}convertDNTMapToArray(e){if(!e||"object"!=typeof e)return[];const t=[];for(const[n,o]of Object.entries(e)){const e=Object.entries(o).map(([e,t])=>({_key:`${n}-${e}`.replace(/[^a-zA-Z0-9-_]/g,"-"),fieldPath:e,dnt:t}));t.push({documentType:n,fields:e})}return t}async load(){try{const e=await this.client.fetch("*[_id == $id][0]",{id:UNIFIED_CONFIG_DOC_ID});if(!e)return console.warn("No unified configuration found in Sanity"),null;let t={};e.dntFieldConfigurations?t=this.convertDNTArrayToMap(e.dntFieldConfigurations):e.dntFieldMap&&(t=e.dntFieldMap);const n={projectId:e.projectId,accessToken:e.accessToken,translationApiEndpoint:e.translationApiEndpoint,requestContentType:e.requestContentType,responseAcceptHeader:e.responseAcceptHeader,defaultDocumentCreationMode:e.defaultDocumentCreationMode,collisionResolutionMode:e.collisionResolutionMode||"replace",existingDocumentHandling:e.existingDocumentHandling||"draft",locales:e.locales||[],defaultLocale:e.defaultLocale,dntFieldMap:t,debugMode:e.debugMode||!1,autoTranslateDocumentTypes:e.autoTranslateDocumentTypes||[],version:e.version||"1.0.0",lastUpdated:e.lastUpdated};return console.log("Loaded unified configuration from Sanity"),n}catch(e){throw console.error("Failed to load unified configuration from Sanity:",e),e}}async save(e){try{const t=this.convertDNTMapToArray(e.dntFieldMap),n={_id:UNIFIED_CONFIG_DOC_ID,_type:UNIFIED_CONFIG_DOC_TYPE,projectId:e.projectId,accessToken:e.accessToken,translationApiEndpoint:e.translationApiEndpoint,requestContentType:e.requestContentType,responseAcceptHeader:e.responseAcceptHeader,defaultDocumentCreationMode:e.defaultDocumentCreationMode,collisionResolutionMode:e.collisionResolutionMode,existingDocumentHandling:e.existingDocumentHandling,locales:e.locales,defaultLocale:e.defaultLocale,dntFieldConfigurations:t,debugMode:e.debugMode,autoTranslateDocumentTypes:e.autoTranslateDocumentTypes||[],version:e.version,lastUpdated:(new Date).toISOString()};await this.client.createOrReplace(n),console.log("Saved unified configuration to Sanity")}catch(e){throw console.error("Failed to save unified configuration to Sanity:",e),e}}async update(e){try{const t={...await this.load()||{},...e,lastUpdated:(new Date).toISOString()};await this.save(t)}catch(e){throw console.error("Failed to update unified configuration:",e),e}}async delete(){try{await this.client.delete(UNIFIED_CONFIG_DOC_ID),console.log("Deleted unified configuration from Sanity")}catch(e){throw console.error("Failed to delete unified configuration from Sanity:",e),e}}async loadOAuth(){const e=await this.load();return e&&e.projectId&&e.accessToken?{projectId:e.projectId,accessToken:e.accessToken}:null}async saveOAuth(e){await this.update({projectId:e.projectId,accessToken:e.accessToken})}async loadLocale(){const e=await this.load();return e?{locales:e.locales||[],defaultLocale:e.defaultLocale,version:e.version||"1.0.0",lastUpdated:e.lastUpdated||(new Date).toISOString()}:null}async saveLocale(e){await this.update({locales:e.locales,defaultLocale:e.defaultLocale})}async getDNTFieldsForType(e){const t=await this.load();return t?.dntFieldMap?.[e]||{}}async setDNTField(e,t,n){const o=(await this.load()||{}).dntFieldMap||{};o[e]||(o[e]={}),o[e][t]=n,await this.update({dntFieldMap:o})}async toggleDNTField(e,t){const n=(await this.load()||{}).dntFieldMap||{};n[e]||(n[e]={});const o=n[e][t]||!1;return n[e][t]=!o,await this.update({dntFieldMap:n}),n[e][t]}async getDNTFieldStatus(e,t){return(await this.getDNTFieldsForType(e))[t]||!1}async clearDNTFieldsForType(e){const t=(await this.load()||{}).dntFieldMap||{};delete t[e],await this.update({dntFieldMap:t})}async getAllDNTFields(){const e=await this.load();return e?.dntFieldMap||{}}async getTranslationEndpoint(){const e=await this.load();return e?.translationApiEndpoint||"https://app.easyling.com/_el/ext/direct/sanity"}async getRequestContentType(){const e=await this.load();return e?.requestContentType||"application/json"}async getResponseAcceptHeader(){const e=await this.load();return e?.responseAcceptHeader||"application/json"}async getDefaultDocumentCreationMode(){const e=await this.load();return e?.defaultDocumentCreationMode||"draft"}async getCollisionResolutionMode(){const e=await this.load();return e?.collisionResolutionMode||"replace"}async getExistingDocumentHandling(){const e=await this.load();return e?.existingDocumentHandling||"draft"}async getCollisionResolutionConfig(){const e=await this.load();return{collisionResolutionMode:e?.collisionResolutionMode||"replace",existingDocumentHandling:e?.existingDocumentHandling||"draft"}}async setCollisionResolutionConfig(e,t){const n={collisionResolutionMode:e};void 0!==t&&(n.existingDocumentHandling=t),await this.update(n)}async getDebugMode(){const e=await this.load();return e?.debugMode||!1}async setDebugMode(e){await this.update({debugMode:e})}async getAutoTranslateDocumentTypes(){const e=await this.load();return e?.autoTranslateDocumentTypes||[]}async setAutoTranslateDocumentTypes(e){await this.update({autoTranslateDocumentTypes:e})}}class HtmlFormatter{static escapeHtml(e){if("string"!=typeof e)return"";const t={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`"};return e.replace(/[&<>"'`/]/g,e=>t[e]||e)}static unescapeHtml(e){if("string"!=typeof e)return"";const t={"&":"&","<":"<",">":">",""":'"',"'":"'","/":"/","`":"`"};return e.replace(/&(?:amp|lt|gt|quot|#x27|#x2F|#x60);/g,e=>t[e]||e)}static formatHtml(e,t={}){if("string"!=typeof e)return"";const{preserveWhitespace:n=!0,escapeSpecialChars:o=!1,minifyOutput:r=!1,addLineBreaks:s=!0}=t;let a=e;return o&&(a=this.escapeHtml(a)),n||(a=a.replace(/\s+/g," ").trim()),s&&!r&&(a=a.replace(/(<\/(?:p|div|h[1-6]|li|blockquote)>)/g,"$1\n").replace(/(<(?:p|div|h[1-6]|li|blockquote)[^>]*>)/g,"\n$1").replace(/(<br\s*\/?>)/g,"$1\n").replace(/\n\s*\n/g,"\n").trim()),r&&(a=a.replace(/>\s+</g,"><").replace(/\s+/g," ").trim()),a}static cleanHtml(e,t=[]){if("string"!=typeof e)return"";const n=t.length>0?t:["p","div","span","h1","h2","h3","h4","h5","h6","strong","em","u","code","pre","blockquote","ul","ol","li","a","img","figure","figcaption","time","br"],o=new RegExp(`<(?!/?(?:${n.join("|")})(?:\\s|>))[^>]+>`,"gi");return e.replace(o,"")}static wrapContent(e,t="div",n){return"string"!=typeof e?"":`<${t}${n?` class="${this.escapeHtml(n)}"`:""}>${e}</${t}>`}static stripHtml(e){return"string"!=typeof e?"":e.replace(/<[^>]*>/g,"").replace(/&[^;]+;/g," ").replace(/\s+/g," ").trim()}static validateHtml(e){const t=[];return"string"!=typeof e?(t.push("HTML content must be a string"),{isValid:!1,errors:t}):((e.includes("<>")||e.includes("</>"))&&t.push("Malformed HTML tags detected"),(e.match(/</g)||[]).length!==(e.match(/>/g)||[]).length&&t.push("Mismatched angle brackets detected"),{isValid:0===t.length,errors:t})}static lineBreaksToParagraphs(e){return"string"!=typeof e?"":e.split(/\n\s*\n/).filter(e=>e.trim()).map(e=>`<p>${this.escapeHtml(e.trim())}</p>`).join("\n")}static truncateHtml(e,t,n="..."){if("string"!=typeof e||e.length<=t)return e;if(this.stripHtml(e).length<=t)return e;const o=e.substring(0,t),r=o.lastIndexOf(">");return r>0?o.substring(0,r+1)+n:o+n}}const htmlFormatter={escapeHtml:HtmlFormatter.escapeHtml,unescapeHtml:HtmlFormatter.unescapeHtml,formatHtml:HtmlFormatter.formatHtml,cleanHtml:HtmlFormatter.cleanHtml,wrapContent:HtmlFormatter.wrapContent,stripHtml:HtmlFormatter.stripHtml,validateHtml:HtmlFormatter.validateHtml,lineBreaksToParagraphs:HtmlFormatter.lineBreaksToParagraphs,truncateHtml:HtmlFormatter.truncateHtml};class Validator{static validateSanityDocument(e,t={}){const n=[],o=[],{requireTitle:r=!1,requireContent:s=!1,allowEmptyFields:a=!0,maxContentLength:i=1e6}=t;if(!e)return n.push("Document is null or undefined"),{isValid:!1,errors:n,warnings:o};if(e._id||n.push("Document missing required _id field"),e._type||n.push("Document missing required _type field"),e._id&&"string"==typeof e._id?0===e._id.length?n.push("Document _id cannot be empty"):/^[a-zA-Z0-9._-]+$/.test(e._id)||o.push("Document _id contains unusual characters"):e._id&&n.push("Document _id must be a string"),e._type&&"string"!=typeof e._type&&n.push("Document _type must be a string"),r&&(["title","name","heading","label"].some(t=>e[t]&&"string"==typeof e[t]&&e[t].trim())||n.push("Document missing required title field")),s&&(["body","content","text","description"].some(t=>{const n=e[t];return n&&("string"==typeof n&&n.trim()||Array.isArray(n)&&n.length>0||"object"==typeof n&&Object.keys(n).length>0)})||n.push("Document missing required content fields")),!a)for(const[t,n]of Object.entries(e))t.startsWith("_")||null!=n&&""!==n||o.push(`Document field '${t}' is empty`);try{const t=JSON.stringify(e).length;t>i&&n.push(`Document size (${t} bytes) exceeds maximum allowed (${i} bytes)`)}catch(e){if(!(e instanceof Error&&e.message.includes("circular")))throw e;n.push("Document contains circular references")}return{isValid:0===n.length,errors:n,warnings:o}}static validateDocumentContent(e){const t=[],n=[];return e?(e.documentId?"string"!=typeof e.documentId&&t.push("Document content documentId must be a string"):t.push("Document content missing documentId"),e.title?"string"!=typeof e.title&&t.push("Document content title must be a string"):n.push("Document content missing title"),void 0===e.htmlContent||null===e.htmlContent?t.push("Document content missing htmlContent"):"string"!=typeof e.htmlContent?t.push("Document content htmlContent must be a string"):""===e.htmlContent.trim()&&n.push("Document content htmlContent is empty"),{isValid:0===t.length,errors:t,warnings:n}):(t.push("Document content is null or undefined"),{isValid:!1,errors:t,warnings:n})}static validateExtendedDocumentContent(e){const t=[],n=[],o=this.validateDocumentContent(e);return t.push(...o.errors),n.push(...o.warnings),void 0!==e.slug&&"string"!=typeof e.slug&&t.push("Extended document content slug must be a string"),void 0!==e.fields&&("object"!=typeof e.fields||null===e.fields?t.push("Extended document content fields must be an object"):Array.isArray(e.fields)&&t.push("Extended document content fields must be an object, not an array")),{isValid:0===t.length,errors:t,warnings:n}}static validateTranslationPayload(e,t={}){const n=[],o=[],{requireMetadata:r=!0,maxPayloadSize:s=1e7,validateHtmlStructure:a=!0}=t;if(!e)return n.push("Translation payload is null or undefined"),{isValid:!1,errors:n,warnings:o};if(e.content?"object"!=typeof e.content?n.push("Translation payload content must be an object"):(e.content.body?"string"!=typeof e.content.body&&n.push("Translation payload content body must be a string"):n.push("Translation payload content missing body field"),e.content.title?"string"!=typeof e.content.title&&n.push("Translation payload content title must be a string"):o.push("Translation payload content missing title field"),void 0!==e.content.slug&&"string"!=typeof e.content.slug&&n.push("Translation payload content slug must be a string"),void 0!==e.content.fields&&("object"==typeof e.content.fields&&null!==e.content.fields||n.push("Translation payload content fields must be an object"))):n.push("Translation payload missing content field"),e.format?"html"!==e.format&&n.push('Translation payload format must be "html"'):n.push("Translation payload missing format field"),r&&(e.metadata?"object"!=typeof e.metadata?n.push("Translation payload metadata must be an object"):(e.metadata.documentId||n.push("Translation payload metadata missing documentId"),e.metadata.documentType||n.push("Translation payload metadata missing documentType"),e.metadata.title||o.push("Translation payload metadata missing title"),e.metadata.sourceLanguage&&"string"!=typeof e.metadata.sourceLanguage&&n.push("Translation payload metadata sourceLanguage must be a string"),e.metadata.targetLanguage&&"string"!=typeof e.metadata.targetLanguage&&n.push("Translation payload metadata targetLanguage must be a string")):n.push("Translation payload missing metadata field")),a&&e.content?.body){const t=this.validateHtmlContent(e.content.body);t.isValid||o.push(...t.errors.map(e=>`HTML validation: ${e}`))}try{const t=JSON.stringify(e).length;t>s&&n.push(`Translation payload size (${t} bytes) exceeds maximum allowed (${s} bytes)`)}catch(e){n.push("Translation payload cannot be serialized to JSON")}return{isValid:0===n.length,errors:n,warnings:o}}static validateHtmlContent(e){const t=[],n=[];if("string"!=typeof e)return t.push("HTML content must be a string"),{isValid:!1,errors:t,warnings:n};(e.includes("<>")||e.includes("</>"))&&t.push("Malformed HTML tags detected"),(e.match(/</g)||[]).length!==(e.match(/>/g)||[]).length&&n.push("Mismatched angle brackets detected");const o=e.replace(/<[^>]*>/g,"").match(/[<>]/g);return o&&o.length>0&&n.push("Unescaped special characters found in HTML text content"),""===e.replace(/<[^>]*>/g,"").trim()&&n.push("HTML content appears to be empty after stripping tags"),{isValid:0===t.length,errors:t,warnings:n}}static validateDocumentArray(e,t={}){const n=[],o=[];if(!Array.isArray(e))return n.push("Documents must be provided as an array"),{isValid:!1,errors:n,warnings:o};if(0===e.length)return o.push("Document array is empty"),{isValid:!0,errors:n,warnings:o};const r=new Set;return e.forEach((e,s)=>{const a=this.validateSanityDocument(e,t);a.errors.forEach(e=>{n.push(`Document ${s}: ${e}`)}),a.warnings.forEach(e=>{o.push(`Document ${s}: ${e}`)}),e?._id&&(r.has(e._id)?n.push(`Duplicate document ID found: ${e._id}`):r.add(e._id))}),{isValid:0===n.length,errors:n,warnings:o}}static validateEndpoint(e){const t=[],n=[];if(!e)return t.push("Endpoint URL is required"),{isValid:!1,errors:t,warnings:n};if("string"!=typeof e)return t.push("Endpoint URL must be a string"),{isValid:!1,errors:t,warnings:n};try{const o=new URL(e);["http:","https:"].includes(o.protocol)||t.push("Endpoint URL must use HTTP or HTTPS protocol"),"localhost"!==o.hostname&&"127.0.0.1"!==o.hostname||n.push("Using localhost endpoint - ensure this is intended for development")}catch(e){t.push("Invalid endpoint URL format")}return{isValid:0===t.length,errors:t,warnings:n}}}const validator={validateSanityDocument:Validator.validateSanityDocument,validateDocumentContent:Validator.validateDocumentContent,validateExtendedDocumentContent:Validator.validateExtendedDocumentContent,validateTranslationPayload:Validator.validateTranslationPayload,validateHtmlContent:Validator.validateHtmlContent,validateDocumentArray:Validator.validateDocumentArray,validateEndpoint:Validator.validateEndpoint};class ConfigurationError extends Error{constructor(e){super(e),this.name="ConfigurationError"}}async function loadConfiguration(e){return new UnifiedConfigStorage(e).load()}function validateConfiguration(e){if(!e)throw new ConfigurationError("Configuration not found in Sanity dataset");if(!e.projectId)throw new ConfigurationError("Missing required field: projectId");if(!e.accessToken)throw new ConfigurationError("Missing required field: accessToken");const t=(e.locales??[]).filter(e=>e.enabled).map(e=>e.code);if(0===t.length)throw new ConfigurationError("No enabled target locales found in configuration");return{targetLocales:t,sourceLocale:e.defaultLocale,projectId:e.projectId,accessToken:e.accessToken,translationEndpoint:e.translationApiEndpoint??"https://app.easyling.com/_el/ext/direct/sanity",autoTranslateDocumentTypes:e.autoTranslateDocumentTypes??[],requestContentType:e.requestContentType??"application/json",responseAcceptHeader:e.responseAcceptHeader??"application/json",defaultDocumentCreationMode:e.defaultDocumentCreationMode??"draft"}}function formatLogEntry(e,t,n){const o={timestamp:(new Date).toISOString(),level:e,message:t,...n&&{context:n}};return JSON.stringify(o)}function info(e,t){console.log(formatLogEntry("info",e,t))}function warn(e,t){console.warn(formatLogEntry("warn",e,t))}function error(e,t){console.error(formatLogEntry("error",e,t))}function createLogger(e){return{info:(t,n)=>{info(t,{...e,...n})},warn:(t,n)=>{warn(t,{...e,...n})},error:(t,n)=>{error(t,{...e,...n})}}}const logger={info,warn,error,createLogger},EXECUTION_DEADLINE_MS=12e4,WARNING_THRESHOLD_MS=1e5,TERMINATION_THRESHOLD_MS=11e4,DOCUMENT_SIZE_LIMIT_BYTES=10485760;function checkDeadline(e,t){const n=Date.now()-e,o=n>WARNING_THRESHOLD_MS,r=n>TERMINATION_THRESHOLD_MS;return r?t.error("Execution deadline approaching – terminating gracefully",{elapsedMs:n,deadlineMs:EXECUTION_DEADLINE_MS,thresholdMs:TERMINATION_THRESHOLD_MS}):o&&t.warn("Execution time approaching deadline",{elapsedMs:n,deadlineMs:EXECUTION_DEADLINE_MS,warningThresholdMs:WARNING_THRESHOLD_MS}),{warning:o,shouldTerminate:r,elapsed:n}}function shouldTranslate(e,t){return!!e?._type&&(!t.autoTranslateDocumentTypes?.length||t.autoTranslateDocumentTypes.includes(e._type))}function buildClient(e){return __WEBPACK_EXTERNAL_MODULE__sanity_client_02883fb2_createClient__({...e,apiVersion:"2025-05-08",useCdn:!1})}async function translateOnPublish(e,t){const n=Date.now(),o={totalInvocations:1,successfulTranslations:0,failedTranslations:0,skippedTranslations:0,localeMetrics:{},errorsByStage:{}},r=e.data,s=buildClient(t.clientOptions),a=logger.createLogger({documentId:r._id,documentType:r._type,operation:"translateOnPublish"});a.info("Function invoked",{documentId:r._id,documentType:r._type,startTime:n});try{t.clientOptions.token||a.warn('No auth token in clientOptions – the client cannot read non-public documents. If running locally, use --with-user-token or enable "With Token" in the dev playground.'),a.info("Loading configuration from Sanity dataset");const e=await loadConfiguration(s);let i;try{i=validateConfiguration(e),a.info("Configuration validated",{targetLocales:i.targetLocales,autoTranslateDocumentTypes:i.autoTranslateDocumentTypes})}catch(e){throw o.errorsByStage.configurationValidation=(o.errorsByStage.configurationValidation??0)+1,a.error("Configuration validation failed",{error:e instanceof Error?e.message:String(e),metrics:o}),e}if(!shouldTranslate(r,i))return o.skippedTranslations++,a.info("Document type not configured for auto-translation",{documentType:r._type,configuredTypes:i.autoTranslateDocumentTypes,metrics:o}),{success:!0,skipped:!0,reason:"Document type not in autoTranslateDocumentTypes",metrics:o};const{targetLocales:l}=i;if(0===l.length)throw o.errorsByStage.configurationValidation=(o.errorsByStage.configurationValidation??0)+1,a.error("No enabled target locales found",{metrics:o}),new ConfigurationError("No enabled target locales found in configuration");const c=JSON.stringify(r).length;if(c>DOCUMENT_SIZE_LIMIT_BYTES)return o.skippedTranslations++,o.errorsByStage.sizeLimit=(o.errorsByStage.sizeLimit??0)+1,a.warn("Document exceeds size limit – skipping translation",{documentSizeBytes:c,limitBytes:DOCUMENT_SIZE_LIMIT_BYTES,metrics:o}),{success:!0,skipped:!0,reason:"Document exceeds size limit",documentSizeBytes:c,limitBytes:DOCUMENT_SIZE_LIMIT_BYTES,metrics:o};a.info("Starting translation workflow",{targetLocales:l,sourceLocale:i.sourceLocale});let u=checkDeadline(n,a);if(u.shouldTerminate)return o.skippedTranslations++,o.errorsByStage.timeout=(o.errorsByStage.timeout??0)+1,{success:!0,skipped:!0,reason:"Execution deadline approaching",elapsedMs:u.elapsed,metrics:o};a.info("Extracting document content");const d=new ContentExtractor;let f;try{f=await d.extractStructuredContent(r),a.info("Content extracted successfully",{hasTitle:!!f.title,hasHtmlContent:!!f.htmlContent,fieldCount:Object.keys(f.fields??{}).length})}catch(e){throw o.errorsByStage.contentExtraction=(o.errorsByStage.contentExtraction??0)+1,a.error("Content extraction failed",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,metrics:o}),e}a.info("Initializing translation service",{endpoint:i.translationEndpoint,requestContentType:i.requestContentType,responseAcceptHeader:i.responseAcceptHeader});const p=new TranslationService(i.translationEndpoint,i.requestContentType,i.responseAcceptHeader);if(p.setAuthToken(i.accessToken,i.projectId),u=checkDeadline(n,a),u.shouldTerminate)return o.skippedTranslations++,o.errorsByStage.timeout=(o.errorsByStage.timeout??0)+1,{success:!0,skipped:!0,reason:"Execution deadline approaching before translation",elapsedMs:u.elapsed,metrics:o};let h,g;a.info("Sending translation request",{targetLocales:l,sourceLocale:i.sourceLocale});try{if(h=await p.translateDocument(f,r._type,i.sourceLocale,void 0,l),!h.success)throw o.failedTranslations++,o.errorsByStage.translationService=(o.errorsByStage.translationService??0)+1,a.error("Translation request failed",{error:h.error,requestId:h.requestId,metrics:o}),new Error(`Translation request failed: ${h.error??"unknown error"}`);a.info("Translation completed successfully",{translatedDocumentCount:h.translatedDocuments?.length??0,requestId:h.requestId})}catch(e){throw o.failedTranslations++,o.errorsByStage.translationService=(o.errorsByStage.translationService??0)+1,a.error("Translation service call failed",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,metrics:o}),e}try{g=new DocumentCreationService(s,i.defaultDocumentCreationMode)}catch(e){throw o.errorsByStage.documentCreation=(o.errorsByStage.documentCreation??0)+1,a.error("Failed to initialize DocumentCreationService",{error:e instanceof Error?e.message:String(e),metrics:o}),e}const m=[];if(u=checkDeadline(n,a),u.shouldTerminate)return o.skippedTranslations++,o.errorsByStage.timeout=(o.errorsByStage.timeout??0)+1,{success:!0,skipped:!0,reason:"Execution deadline approaching before document creation",elapsedMs:u.elapsed,translationCompleted:!0,metrics:o};for(const e of h.translatedDocuments??[]){const t=e.locale;if(t&&!o.localeMetrics[t]&&(o.localeMetrics[t]={successCount:0,failureCount:0}),u=checkDeadline(n,a),u.shouldTerminate)return o.errorsByStage.timeout=(o.errorsByStage.timeout??0)+1,o.successfulTranslations=m.filter(e=>e.success).length,o.failedTranslations=m.filter(e=>!e.success).length,{success:!0,results:m,summary:{successCount:m.filter(e=>e.success).length,failureCount:m.filter(e=>!e.success).length,totalCount:m.length,partial:!0,reason:"Execution deadline approaching"},elapsedMs:u.elapsed,metrics:o};a.info("Creating translated document",{targetLocale:t,parentDocumentId:r._id});try{const n=await g.createDocumentFromTranslation(r,{...h,translatedDocuments:[e]},{targetLanguage:t,parentDocumentId:r._id,creationMode:i.defaultDocumentCreationMode});n.success?(o.successfulTranslations++,t&&o.localeMetrics[t].successCount++,a.info("Translated document created successfully",{targetLocale:t,documentId:n.documentId,slugFallback:n.slugFallback}),m.push({locale:t,documentId:n.documentId,success:!0})):(o.failedTranslations++,o.errorsByStage.documentCreation=(o.errorsByStage.documentCreation??0)+1,t&&o.localeMetrics[t].failureCount++,a.error("Failed to create translated document",{targetLocale:t,error:n.error,metrics:o}),m.push({locale:t,success:!1,error:n.error}))}catch(e){o.failedTranslations++,o.errorsByStage.documentCreation=(o.errorsByStage.documentCreation??0)+1,t&&o.localeMetrics[t].failureCount++,a.error("Exception while creating translated document",{targetLocale:t,error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,metrics:o}),m.push({locale:t,success:!1,error:e instanceof Error?e.message:String(e)})}}const y=m.filter(e=>e.success).length,b=m.filter(e=>!e.success).length,T=Date.now()-n;if(0===y&&b>0)throw a.error("Translation workflow failed – all locales failed",{totalResults:m.length,failureCount:b,elapsedMs:T,metrics:o}),new Error(`Translation failed for all ${b} locale(s): `+m.map(e=>`${e.locale}: ${e.error}`).join("; "));return a[b>0?"warn":"info"]("Translation workflow completed",{totalResults:m.length,successCount:y,failureCount:b,elapsedMs:T,metrics:o}),{success:0===b,results:m,summary:{successCount:y,failureCount:b,totalCount:m.length},elapsedMs:T,metrics:o}}catch(e){throw o.failedTranslations++,o.errorsByStage.other=(o.errorsByStage.other??0)+1,a.error("Translation workflow failed with exception",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,metrics:o}),e}}export{translateOnPublish as default,shouldTranslate};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|