@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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","mappings":"iJAMA,IAAIA,EAAmBC,MAAQA,KAAKD,iBAAoB,SAAUE,GAC9D,OAAQA,GAAOA,EAAIC,WAAcD,EAAM,CAAE,QAAWA,EACxD,EACAE,OAAOC,eAAeC,EAAS,aAAc,CAAEC,OAAO,IACtDD,EAAQE,SAAWF,EAAQG,kBAAoBH,EAAQI,oBAAsBJ,EAAQK,QAAUL,EAAQM,0BAA4BN,EAAQO,qBAAuB,EAElK,MAAMC,EAAYd,EAAgB,EAAQ,MAsf1C,SAASe,EAAMR,GACX,OAAOA,OACX,CAvfAD,EAAQO,gBAAkB,mDAI1BP,EAAQM,0BAA4B,CAChCI,OAAM,CAACC,EAASC,EAASJ,EAAUK,QAAQC,OAAOC,iBACtBC,IAApBL,EAAQM,SACRjB,EAAQK,QAAQK,OAAOC,EAAQM,QAASL,EAAOM,OAAO,IAAIC,QAAQC,SAE9C,KAApBT,EAAQU,SACRT,EAAOM,OAAO,IAAII,OAAOX,EAAQU,SAEd,KAAnBV,EAAQY,QACRX,EAAOM,OAAO,IAAII,OAAOX,EAAQY,aAEZP,IAArBL,EAAQa,UACRxB,EAAQE,SAASQ,OAAOC,EAAQa,SAAUZ,EAAOM,OAAO,IAAIC,QAAQC,SAEjER,GAEX,MAAAa,CAAOC,EAAOC,GACV,MAAMC,EAASF,aAAiBlB,EAAUK,QAAQgB,OAASH,EAAQlB,EAAUK,QAAQgB,OAAOd,OAAOW,GACnG,IAAII,OAAiBd,IAAXW,EAAuBC,EAAOG,IAAMH,EAAOI,IAAML,EAC3D,MAAMhB,EArBH,CAAEM,aAASD,EAAWK,QAAS,GAAIE,OAAQ,GAAIC,cAAUR,GAsB5D,KAAOY,EAAOI,IAAMF,GAAK,CACrB,MAAMG,EAAML,EAAOV,SACn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,GAAsBC,EAAe,EAOvC,MANAvvB,EAAIzE,MAAM,mDAAoD,CAC5Dq0B,aAActd,EAAQja,OACtBk3B,eACAvC,UAAW2C,EACXjC,YAEI,IAAI7vB,MACR,8BAA8B0xB,gBAC9Bjd,EAAQxX,IAAK00B,GAAM,GAAGA,EAAE/zB,WAAW+zB,EAAEj0B,SAASkC,KAAK,OAavD,OARAuC,EADyBuvB,EAAe,EAAI,OAAS,QAC/B,iCAAkC,CACtDK,aAActd,EAAQja,OACtBi3B,eACAC,eACAvC,UAAW2C,EACXjC,YAGK,CACLtyB,QAA0B,IAAjBm0B,EACTjd,UACAgG,QAAS,CAAEgX,eAAcC,eAAcE,WAAYnd,EAAQja,QAC3D20B,UAAW2C,EACXjC,UAEJ,CAAE,MAAOnyB,GAQP,MAPAmyB,EAAQG,qBACRH,EAAQM,cAAc6B,OAASnC,EAAQM,cAAc6B,OAAS,GAAK,EACnE7vB,EAAIzE,MAAM,6CAA8C,CACtDA,MAAOA,aAAiBsC,MAAQtC,EAAMlE,QAAU2B,OAAOuC,GACvDkN,MAAOlN,aAAiBsC,MAAQtC,EAAMkN,WAAQ/Q,EAC9Cg2B,YAEInyB,CACR,CACF,Q","sources":["webpack://@easyling/sanity-auto-translate/../node_modules/@easyling/protos-sanity/dist/generated/translation_request.js","webpack://@easyling/sanity-auto-translate/../node_modules/@easyling/protos-sanity/dist/generated/translation_response.js","webpack://@easyling/sanity-auto-translate/../node_modules/@protobufjs/aspromise/index.js","webpack://@easyling/sanity-auto-translate/../node_modules/@protobufjs/base64/index.js","webpack://@easyling/sanity-auto-translate/../node_modules/@protobufjs/eventemitter/index.js","webpack://@easyling/sanity-auto-translate/../node_modules/@protobufjs/float/index.js","webpack://@easyling/sanity-auto-translate/../node_modules/@protobufjs/inquire/index.js","webpack://@easyling/sanity-auto-translate/../node_modules/@protobufjs/pool/index.js","webpack://@easyling/sanity-auto-translate/../node_modules/@protobufjs/utf8/index.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/minimal.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/index-minimal.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/reader.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/reader_buffer.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/roots.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/rpc.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/rpc/service.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/util/longbits.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/util/minimal.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/writer.js","webpack://@easyling/sanity-auto-translate/../node_modules/protobufjs/src/writer_buffer.js","webpack://@easyling/sanity-auto-translate/webpack/bootstrap","webpack://@easyling/sanity-auto-translate/webpack/runtime/define property getters","webpack://@easyling/sanity-auto-translate/webpack/runtime/hasOwnProperty shorthand","webpack://@easyling/sanity-auto-translate/javascript/esm|D:\\Projects\\sanity-plugin\\shared\\dist\\services\\contentExtractor.js","webpack://@easyling/sanity-auto-translate/javascript/esm|D:\\Projects\\sanity-plugin\\shared\\dist\\services\\translationService.js","webpack://@easyling/sanity-auto-translate/javascript/esm|D:\\Projects\\sanity-plugin\\shared\\dist\\services\\collisionDetectionService.js","webpack://@easyling/sanity-auto-translate/javascript/esm|D:\\Projects\\sanity-plugin\\shared\\dist\\services\\documentCreationService.js","webpack://@easyling/sanity-auto-translate/javascript/esm|D:\\Projects\\sanity-plugin\\shared\\dist\\services\\unifiedConfigStorage.js","webpack://@easyling/sanity-auto-translate/javascript/esm|D:\\Projects\\sanity-plugin\\shared\\dist\\utils\\htmlFormatter.js","webpack://@easyling/sanity-auto-translate/javascript/esm|D:\\Projects\\sanity-plugin\\shared\\dist\\utils\\validator.js","webpack://@easyling/sanity-auto-translate/./src/config.ts","webpack://@easyling/sanity-auto-translate/./src/logger.ts","webpack://@easyling/sanity-auto-translate/./src/index.ts"],"sourcesContent":["\"use strict\";\n// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v1.181.2\n// protoc v3.21.8\n// source: translation_request.proto\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Metadata = exports.TranslatableField = exports.Content_FieldsEntry = exports.Content = exports.TranslationRequestPayload = exports.protobufPackage = void 0;\n/* eslint-disable */\nconst minimal_1 = __importDefault(require(\"protobufjs/minimal\"));\nexports.protobufPackage = \"hu.skawa.pagetranslate.server.model.protobuffers\";\nfunction createBaseTranslationRequestPayload() {\n return { content: undefined, project: \"\", format: \"\", metadata: undefined };\n}\nexports.TranslationRequestPayload = {\n encode(message, writer = minimal_1.default.Writer.create()) {\n if (message.content !== undefined) {\n exports.Content.encode(message.content, writer.uint32(10).fork()).ldelim();\n }\n if (message.project !== \"\") {\n writer.uint32(34).string(message.project);\n }\n if (message.format !== \"\") {\n writer.uint32(18).string(message.format);\n }\n if (message.metadata !== undefined) {\n exports.Metadata.encode(message.metadata, writer.uint32(26).fork()).ldelim();\n }\n return writer;\n },\n decode(input, length) {\n const reader = input instanceof minimal_1.default.Reader ? input : minimal_1.default.Reader.create(input);\n let end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTranslationRequestPayload();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n if (tag !== 10) {\n break;\n }\n message.content = exports.Content.decode(reader, reader.uint32());\n continue;\n case 4:\n if (tag !== 34) {\n break;\n }\n message.project = reader.string();\n continue;\n case 2:\n if (tag !== 18) {\n break;\n }\n message.format = reader.string();\n continue;\n case 3:\n if (tag !== 26) {\n break;\n }\n message.metadata = exports.Metadata.decode(reader, reader.uint32());\n continue;\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skipType(tag & 7);\n }\n return message;\n },\n fromJSON(object) {\n return {\n content: isSet(object.content) ? exports.Content.fromJSON(object.content) : undefined,\n project: isSet(object.project) ? globalThis.String(object.project) : \"\",\n format: isSet(object.format) ? globalThis.String(object.format) : \"\",\n metadata: isSet(object.metadata) ? exports.Metadata.fromJSON(object.metadata) : undefined,\n };\n },\n toJSON(message) {\n const obj = {};\n if (message.content !== undefined) {\n obj.content = exports.Content.toJSON(message.content);\n }\n if (message.project !== \"\") {\n obj.project = message.project;\n }\n if (message.format !== \"\") {\n obj.format = message.format;\n }\n if (message.metadata !== undefined) {\n obj.metadata = exports.Metadata.toJSON(message.metadata);\n }\n return obj;\n },\n create(base) {\n return exports.TranslationRequestPayload.fromPartial(base ?? {});\n },\n fromPartial(object) {\n const message = createBaseTranslationRequestPayload();\n message.content = (object.content !== undefined && object.content !== null)\n ? exports.Content.fromPartial(object.content)\n : undefined;\n message.project = object.project ?? \"\";\n message.format = object.format ?? \"\";\n message.metadata = (object.metadata !== undefined && object.metadata !== null)\n ? exports.Metadata.fromPartial(object.metadata)\n : undefined;\n return message;\n },\n};\nfunction createBaseContent() {\n return { body: \"\", title: \"\", slug: \"\", fields: {} };\n}\nexports.Content = {\n encode(message, writer = minimal_1.default.Writer.create()) {\n if (message.body !== \"\") {\n writer.uint32(10).string(message.body);\n }\n if (message.title !== \"\") {\n writer.uint32(18).string(message.title);\n }\n if (message.slug !== \"\") {\n writer.uint32(26).string(message.slug);\n }\n Object.entries(message.fields).forEach(([key, value]) => {\n exports.Content_FieldsEntry.encode({ key: key, value }, writer.uint32(34).fork()).ldelim();\n });\n return writer;\n },\n decode(input, length) {\n const reader = input instanceof minimal_1.default.Reader ? input : minimal_1.default.Reader.create(input);\n let end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseContent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n if (tag !== 10) {\n break;\n }\n message.body = reader.string();\n continue;\n case 2:\n if (tag !== 18) {\n break;\n }\n message.title = reader.string();\n continue;\n case 3:\n if (tag !== 26) {\n break;\n }\n message.slug = reader.string();\n continue;\n case 4:\n if (tag !== 34) {\n break;\n }\n const entry4 = exports.Content_FieldsEntry.decode(reader, reader.uint32());\n if (entry4.value !== undefined) {\n message.fields[entry4.key] = entry4.value;\n }\n continue;\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skipType(tag & 7);\n }\n return message;\n },\n fromJSON(object) {\n return {\n body: isSet(object.body) ? globalThis.String(object.body) : \"\",\n title: isSet(object.title) ? globalThis.String(object.title) : \"\",\n slug: isSet(object.slug) ? globalThis.String(object.slug) : \"\",\n fields: isObject(object.fields)\n ? Object.entries(object.fields).reduce((acc, [key, value]) => {\n acc[key] = exports.TranslatableField.fromJSON(value);\n return acc;\n }, {})\n : {},\n };\n },\n toJSON(message) {\n const obj = {};\n if (message.body !== \"\") {\n obj.body = message.body;\n }\n if (message.title !== \"\") {\n obj.title = message.title;\n }\n if (message.slug !== \"\") {\n obj.slug = message.slug;\n }\n if (message.fields) {\n const entries = Object.entries(message.fields);\n if (entries.length > 0) {\n obj.fields = {};\n entries.forEach(([k, v]) => {\n obj.fields[k] = exports.TranslatableField.toJSON(v);\n });\n }\n }\n return obj;\n },\n create(base) {\n return exports.Content.fromPartial(base ?? {});\n },\n fromPartial(object) {\n const message = createBaseContent();\n message.body = object.body ?? \"\";\n message.title = object.title ?? \"\";\n message.slug = object.slug ?? \"\";\n message.fields = Object.entries(object.fields ?? {}).reduce((acc, [key, value]) => {\n if (value !== undefined) {\n acc[key] = exports.TranslatableField.fromPartial(value);\n }\n return acc;\n }, {});\n return message;\n },\n};\nfunction createBaseContent_FieldsEntry() {\n return { key: \"\", value: undefined };\n}\nexports.Content_FieldsEntry = {\n encode(message, writer = minimal_1.default.Writer.create()) {\n if (message.key !== \"\") {\n writer.uint32(10).string(message.key);\n }\n if (message.value !== undefined) {\n exports.TranslatableField.encode(message.value, writer.uint32(18).fork()).ldelim();\n }\n return writer;\n },\n decode(input, length) {\n const reader = input instanceof minimal_1.default.Reader ? input : minimal_1.default.Reader.create(input);\n let end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseContent_FieldsEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n if (tag !== 10) {\n break;\n }\n message.key = reader.string();\n continue;\n case 2:\n if (tag !== 18) {\n break;\n }\n message.value = exports.TranslatableField.decode(reader, reader.uint32());\n continue;\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skipType(tag & 7);\n }\n return message;\n },\n fromJSON(object) {\n return {\n key: isSet(object.key) ? globalThis.String(object.key) : \"\",\n value: isSet(object.value) ? exports.TranslatableField.fromJSON(object.value) : undefined,\n };\n },\n toJSON(message) {\n const obj = {};\n if (message.key !== \"\") {\n obj.key = message.key;\n }\n if (message.value !== undefined) {\n obj.value = exports.TranslatableField.toJSON(message.value);\n }\n return obj;\n },\n create(base) {\n return exports.Content_FieldsEntry.fromPartial(base ?? {});\n },\n fromPartial(object) {\n const message = createBaseContent_FieldsEntry();\n message.key = object.key ?? \"\";\n message.value = (object.value !== undefined && object.value !== null)\n ? exports.TranslatableField.fromPartial(object.value)\n : undefined;\n return message;\n },\n};\nfunction createBaseTranslatableField() {\n return { value: \"\", dnt: false, type: \"\", path: \"\" };\n}\nexports.TranslatableField = {\n encode(message, writer = minimal_1.default.Writer.create()) {\n if (message.value !== \"\") {\n writer.uint32(10).string(message.value);\n }\n if (message.dnt !== false) {\n writer.uint32(16).bool(message.dnt);\n }\n if (message.type !== \"\") {\n writer.uint32(26).string(message.type);\n }\n if (message.path !== \"\") {\n writer.uint32(34).string(message.path);\n }\n return writer;\n },\n decode(input, length) {\n const reader = input instanceof minimal_1.default.Reader ? input : minimal_1.default.Reader.create(input);\n let end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTranslatableField();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n if (tag !== 10) {\n break;\n }\n message.value = reader.string();\n continue;\n case 2:\n if (tag !== 16) {\n break;\n }\n message.dnt = reader.bool();\n continue;\n case 3:\n if (tag !== 26) {\n break;\n }\n message.type = reader.string();\n continue;\n case 4:\n if (tag !== 34) {\n break;\n }\n message.path = reader.string();\n continue;\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skipType(tag & 7);\n }\n return message;\n },\n fromJSON(object) {\n return {\n value: isSet(object.value) ? globalThis.String(object.value) : \"\",\n dnt: isSet(object.dnt) ? globalThis.Boolean(object.dnt) : false,\n type: isSet(object.type) ? globalThis.String(object.type) : \"\",\n path: isSet(object.path) ? globalThis.String(object.path) : \"\",\n };\n },\n toJSON(message) {\n const obj = {};\n if (message.value !== \"\") {\n obj.value = message.value;\n }\n if (message.dnt !== false) {\n obj.dnt = message.dnt;\n }\n if (message.type !== \"\") {\n obj.type = message.type;\n }\n if (message.path !== \"\") {\n obj.path = message.path;\n }\n return obj;\n },\n create(base) {\n return exports.TranslatableField.fromPartial(base ?? {});\n },\n fromPartial(object) {\n const message = createBaseTranslatableField();\n message.value = object.value ?? \"\";\n message.dnt = object.dnt ?? false;\n message.type = object.type ?? \"\";\n message.path = object.path ?? \"\";\n return message;\n },\n};\nfunction createBaseMetadata() {\n return { documentId: \"\", documentType: \"\", title: \"\", sourceLanguage: \"\", targetLanguage: \"\", targetLocales: [] };\n}\nexports.Metadata = {\n encode(message, writer = minimal_1.default.Writer.create()) {\n if (message.documentId !== \"\") {\n writer.uint32(10).string(message.documentId);\n }\n if (message.documentType !== \"\") {\n writer.uint32(18).string(message.documentType);\n }\n if (message.title !== \"\") {\n writer.uint32(26).string(message.title);\n }\n if (message.sourceLanguage !== \"\") {\n writer.uint32(34).string(message.sourceLanguage);\n }\n if (message.targetLanguage !== \"\") {\n writer.uint32(42).string(message.targetLanguage);\n }\n for (const v of message.targetLocales) {\n writer.uint32(50).string(v);\n }\n return writer;\n },\n decode(input, length) {\n const reader = input instanceof minimal_1.default.Reader ? input : minimal_1.default.Reader.create(input);\n let end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMetadata();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n if (tag !== 10) {\n break;\n }\n message.documentId = reader.string();\n continue;\n case 2:\n if (tag !== 18) {\n break;\n }\n message.documentType = reader.string();\n continue;\n case 3:\n if (tag !== 26) {\n break;\n }\n message.title = reader.string();\n continue;\n case 4:\n if (tag !== 34) {\n break;\n }\n message.sourceLanguage = reader.string();\n continue;\n case 5:\n if (tag !== 42) {\n break;\n }\n message.targetLanguage = reader.string();\n continue;\n case 6:\n if (tag !== 50) {\n break;\n }\n message.targetLocales.push(reader.string());\n continue;\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skipType(tag & 7);\n }\n return message;\n },\n fromJSON(object) {\n return {\n documentId: isSet(object.documentId) ? globalThis.String(object.documentId) : \"\",\n documentType: isSet(object.documentType) ? globalThis.String(object.documentType) : \"\",\n title: isSet(object.title) ? globalThis.String(object.title) : \"\",\n sourceLanguage: isSet(object.sourceLanguage) ? globalThis.String(object.sourceLanguage) : \"\",\n targetLanguage: isSet(object.targetLanguage) ? globalThis.String(object.targetLanguage) : \"\",\n targetLocales: globalThis.Array.isArray(object?.targetLocales)\n ? object.targetLocales.map((e) => globalThis.String(e))\n : [],\n };\n },\n toJSON(message) {\n const obj = {};\n if (message.documentId !== \"\") {\n obj.documentId = message.documentId;\n }\n if (message.documentType !== \"\") {\n obj.documentType = message.documentType;\n }\n if (message.title !== \"\") {\n obj.title = message.title;\n }\n if (message.sourceLanguage !== \"\") {\n obj.sourceLanguage = message.sourceLanguage;\n }\n if (message.targetLanguage !== \"\") {\n obj.targetLanguage = message.targetLanguage;\n }\n if (message.targetLocales?.length) {\n obj.targetLocales = message.targetLocales;\n }\n return obj;\n },\n create(base) {\n return exports.Metadata.fromPartial(base ?? {});\n },\n fromPartial(object) {\n const message = createBaseMetadata();\n message.documentId = object.documentId ?? \"\";\n message.documentType = object.documentType ?? \"\";\n message.title = object.title ?? \"\";\n message.sourceLanguage = object.sourceLanguage ?? \"\";\n message.targetLanguage = object.targetLanguage ?? \"\";\n message.targetLocales = object.targetLocales?.map((e) => e) || [];\n return message;\n },\n};\nfunction isObject(value) {\n return typeof value === \"object\" && value !== null;\n}\nfunction isSet(value) {\n return value !== null && value !== undefined;\n}\n","\"use strict\";\n// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v1.181.2\n// protoc v3.21.8\n// source: translation_response.proto\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TranslatedDocument_FieldsEntry = exports.TranslatedDocument = exports.TranslationResponse = exports.protobufPackage = void 0;\n/* eslint-disable */\nconst minimal_1 = __importDefault(require(\"protobufjs/minimal\"));\nconst translation_request_1 = require(\"./translation_request\");\nexports.protobufPackage = \"hu.skawa.pagetranslate.server.model.protobuffers\";\nfunction createBaseTranslationResponse() {\n return { success: false, translatedDocuments: [], sourceLocale: \"\", error: \"\", requestId: \"\" };\n}\nexports.TranslationResponse = {\n encode(message, writer = minimal_1.default.Writer.create()) {\n if (message.success !== false) {\n writer.uint32(8).bool(message.success);\n }\n for (const v of message.translatedDocuments) {\n exports.TranslatedDocument.encode(v, writer.uint32(18).fork()).ldelim();\n }\n if (message.sourceLocale !== \"\") {\n writer.uint32(26).string(message.sourceLocale);\n }\n if (message.error !== \"\") {\n writer.uint32(34).string(message.error);\n }\n if (message.requestId !== \"\") {\n writer.uint32(42).string(message.requestId);\n }\n return writer;\n },\n decode(input, length) {\n const reader = input instanceof minimal_1.default.Reader ? input : minimal_1.default.Reader.create(input);\n let end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTranslationResponse();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n if (tag !== 8) {\n break;\n }\n message.success = reader.bool();\n continue;\n case 2:\n if (tag !== 18) {\n break;\n }\n message.translatedDocuments.push(exports.TranslatedDocument.decode(reader, reader.uint32()));\n continue;\n case 3:\n if (tag !== 26) {\n break;\n }\n message.sourceLocale = reader.string();\n continue;\n case 4:\n if (tag !== 34) {\n break;\n }\n message.error = reader.string();\n continue;\n case 5:\n if (tag !== 42) {\n break;\n }\n message.requestId = reader.string();\n continue;\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skipType(tag & 7);\n }\n return message;\n },\n fromJSON(object) {\n return {\n success: isSet(object.success) ? globalThis.Boolean(object.success) : false,\n translatedDocuments: globalThis.Array.isArray(object?.translatedDocuments)\n ? object.translatedDocuments.map((e) => exports.TranslatedDocument.fromJSON(e))\n : [],\n sourceLocale: isSet(object.sourceLocale) ? globalThis.String(object.sourceLocale) : \"\",\n error: isSet(object.error) ? globalThis.String(object.error) : \"\",\n requestId: isSet(object.requestId) ? globalThis.String(object.requestId) : \"\",\n };\n },\n toJSON(message) {\n const obj = {};\n if (message.success !== false) {\n obj.success = message.success;\n }\n if (message.translatedDocuments?.length) {\n obj.translatedDocuments = message.translatedDocuments.map((e) => exports.TranslatedDocument.toJSON(e));\n }\n if (message.sourceLocale !== \"\") {\n obj.sourceLocale = message.sourceLocale;\n }\n if (message.error !== \"\") {\n obj.error = message.error;\n }\n if (message.requestId !== \"\") {\n obj.requestId = message.requestId;\n }\n return obj;\n },\n create(base) {\n return exports.TranslationResponse.fromPartial(base ?? {});\n },\n fromPartial(object) {\n const message = createBaseTranslationResponse();\n message.success = object.success ?? false;\n message.translatedDocuments = object.translatedDocuments?.map((e) => exports.TranslatedDocument.fromPartial(e)) || [];\n message.sourceLocale = object.sourceLocale ?? \"\";\n message.error = object.error ?? \"\";\n message.requestId = object.requestId ?? \"\";\n return message;\n },\n};\nfunction createBaseTranslatedDocument() {\n return { body: \"\", title: \"\", slug: \"\", fields: {}, locale: \"\" };\n}\nexports.TranslatedDocument = {\n encode(message, writer = minimal_1.default.Writer.create()) {\n if (message.body !== \"\") {\n writer.uint32(10).string(message.body);\n }\n if (message.title !== \"\") {\n writer.uint32(18).string(message.title);\n }\n if (message.slug !== \"\") {\n writer.uint32(26).string(message.slug);\n }\n Object.entries(message.fields).forEach(([key, value]) => {\n exports.TranslatedDocument_FieldsEntry.encode({ key: key, value }, writer.uint32(34).fork()).ldelim();\n });\n if (message.locale !== \"\") {\n writer.uint32(42).string(message.locale);\n }\n return writer;\n },\n decode(input, length) {\n const reader = input instanceof minimal_1.default.Reader ? input : minimal_1.default.Reader.create(input);\n let end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTranslatedDocument();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n if (tag !== 10) {\n break;\n }\n message.body = reader.string();\n continue;\n case 2:\n if (tag !== 18) {\n break;\n }\n message.title = reader.string();\n continue;\n case 3:\n if (tag !== 26) {\n break;\n }\n message.slug = reader.string();\n continue;\n case 4:\n if (tag !== 34) {\n break;\n }\n const entry4 = exports.TranslatedDocument_FieldsEntry.decode(reader, reader.uint32());\n if (entry4.value !== undefined) {\n message.fields[entry4.key] = entry4.value;\n }\n continue;\n case 5:\n if (tag !== 42) {\n break;\n }\n message.locale = reader.string();\n continue;\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skipType(tag & 7);\n }\n return message;\n },\n fromJSON(object) {\n return {\n body: isSet(object.body) ? globalThis.String(object.body) : \"\",\n title: isSet(object.title) ? globalThis.String(object.title) : \"\",\n slug: isSet(object.slug) ? globalThis.String(object.slug) : \"\",\n fields: isObject(object.fields)\n ? Object.entries(object.fields).reduce((acc, [key, value]) => {\n acc[key] = translation_request_1.TranslatableField.fromJSON(value);\n return acc;\n }, {})\n : {},\n locale: isSet(object.locale) ? globalThis.String(object.locale) : \"\",\n };\n },\n toJSON(message) {\n const obj = {};\n if (message.body !== \"\") {\n obj.body = message.body;\n }\n if (message.title !== \"\") {\n obj.title = message.title;\n }\n if (message.slug !== \"\") {\n obj.slug = message.slug;\n }\n if (message.fields) {\n const entries = Object.entries(message.fields);\n if (entries.length > 0) {\n obj.fields = {};\n entries.forEach(([k, v]) => {\n obj.fields[k] = translation_request_1.TranslatableField.toJSON(v);\n });\n }\n }\n if (message.locale !== \"\") {\n obj.locale = message.locale;\n }\n return obj;\n },\n create(base) {\n return exports.TranslatedDocument.fromPartial(base ?? {});\n },\n fromPartial(object) {\n const message = createBaseTranslatedDocument();\n message.body = object.body ?? \"\";\n message.title = object.title ?? \"\";\n message.slug = object.slug ?? \"\";\n message.fields = Object.entries(object.fields ?? {}).reduce((acc, [key, value]) => {\n if (value !== undefined) {\n acc[key] = translation_request_1.TranslatableField.fromPartial(value);\n }\n return acc;\n }, {});\n message.locale = object.locale ?? \"\";\n return message;\n },\n};\nfunction createBaseTranslatedDocument_FieldsEntry() {\n return { key: \"\", value: undefined };\n}\nexports.TranslatedDocument_FieldsEntry = {\n encode(message, writer = minimal_1.default.Writer.create()) {\n if (message.key !== \"\") {\n writer.uint32(10).string(message.key);\n }\n if (message.value !== undefined) {\n translation_request_1.TranslatableField.encode(message.value, writer.uint32(18).fork()).ldelim();\n }\n return writer;\n },\n decode(input, length) {\n const reader = input instanceof minimal_1.default.Reader ? input : minimal_1.default.Reader.create(input);\n let end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTranslatedDocument_FieldsEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1:\n if (tag !== 10) {\n break;\n }\n message.key = reader.string();\n continue;\n case 2:\n if (tag !== 18) {\n break;\n }\n message.value = translation_request_1.TranslatableField.decode(reader, reader.uint32());\n continue;\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skipType(tag & 7);\n }\n return message;\n },\n fromJSON(object) {\n return {\n key: isSet(object.key) ? globalThis.String(object.key) : \"\",\n value: isSet(object.value) ? translation_request_1.TranslatableField.fromJSON(object.value) : undefined,\n };\n },\n toJSON(message) {\n const obj = {};\n if (message.key !== \"\") {\n obj.key = message.key;\n }\n if (message.value !== undefined) {\n obj.value = translation_request_1.TranslatableField.toJSON(message.value);\n }\n return obj;\n },\n create(base) {\n return exports.TranslatedDocument_FieldsEntry.fromPartial(base ?? {});\n },\n fromPartial(object) {\n const message = createBaseTranslatedDocument_FieldsEntry();\n message.key = object.key ?? \"\";\n message.value = (object.value !== undefined && object.value !== null)\n ? translation_request_1.TranslatableField.fromPartial(object.value)\n : undefined;\n return message;\n },\n};\nfunction isObject(value) {\n return typeof value === \"object\" && value !== null;\n}\nfunction isSet(value) {\n return value !== null && value !== undefined;\n}\n","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.<string,*>}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","// minimal library entry point.\n\n\"use strict\";\nmodule.exports = require(\"./src/index-minimal\");\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(\"./writer\");\nprotobuf.BufferWriter = require(\"./writer_buffer\");\nprotobuf.Reader = require(\"./reader\");\nprotobuf.BufferReader = require(\"./reader_buffer\");\n\n// Utility\nprotobuf.util = require(\"./util/minimal\");\nprotobuf.rpc = require(\"./rpc\");\nprotobuf.roots = require(\"./roots\");\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(\"./util/minimal\");\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(\"./reader\");\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.<string,Root>}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(\"./rpc/service\");\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(\"../util/minimal\");\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message<TRes>\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message<TReq>\n * @template TRes extends Message<TRes>\n * @type {function}\n * @param {TReq|Properties<TReq>} request Request message or plain object\n * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method\n * @param {Constructor<TReq>} requestCtor Request constructor\n * @param {Constructor<TRes>} responseCtor Response constructor\n * @param {TReq|Properties<TReq>} request Request message or plain object\n * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message<TReq>\n * @template TRes extends Message<TRes>\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(\"../util/minimal\");\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(\"@protobufjs/aspromise\");\n\n// converts to / from base64 encoded strings\nutil.base64 = require(\"@protobufjs/base64\");\n\n// base class of rpc.Service\nutil.EventEmitter = require(\"@protobufjs/eventemitter\");\n\n// float handling accross browsers\nutil.float = require(\"@protobufjs/float\");\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(\"@protobufjs/inquire\");\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(\"@protobufjs/utf8\");\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(\"@protobufjs/pool\");\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(\"./longbits\");\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor<Buffer>}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor<Uint8Array>}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor<Long>}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.<string,*>} dst Destination object\n * @param {Object.<string,*>} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.<string,*>} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor<Error>} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message<T>\n * @constructor\n * @param {string} message Error message\n * @param {Object.<string,*>} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message<T>}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(\"./util/minimal\");\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(\"./writer\");\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(\"./util/minimal\");\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// Temporary inline implementation of computeDNTDefault until utils are migrated\nfunction computeDNTDefault(context) {\n const NON_TRANSLATABLE_TYPES = ['date', 'datetime', 'reference', 'image', 'file', 'geopoint', 'number', 'boolean'];\n const DNT_FIELD_NAME_PATTERNS = ['author', 'contributor', 'date', 'time', 'lastModification', 'lastModified', '_key', '_ref', '_type', '_id', '_rev', '_createdAt', '_updatedAt'];\n const DNT_GROUP_NAME_PATTERNS = ['date', 'time'];\n if (context.fieldType && NON_TRANSLATABLE_TYPES.includes(context.fieldType)) {\n return { shouldBeDNT: true, reason: `Field type '${context.fieldType}' is non-translatable` };\n }\n const fieldNameLower = context.fieldName.toLowerCase();\n for (const pattern of DNT_FIELD_NAME_PATTERNS) {\n if (fieldNameLower.includes(pattern.toLowerCase())) {\n return { shouldBeDNT: true, reason: `Field name contains DNT pattern '${pattern}'` };\n }\n }\n if (context.groupName) {\n const groupNameLower = context.groupName.toLowerCase();\n for (const pattern of DNT_GROUP_NAME_PATTERNS) {\n if (groupNameLower.includes(pattern.toLowerCase())) {\n return { shouldBeDNT: true, reason: `Group name contains DNT pattern '${pattern}'` };\n }\n }\n }\n if (context.fieldsetName) {\n const fieldsetNameLower = context.fieldsetName.toLowerCase();\n for (const pattern of DNT_GROUP_NAME_PATTERNS) {\n if (fieldsetNameLower.includes(pattern.toLowerCase())) {\n return { shouldBeDNT: true, reason: `Fieldset name contains DNT pattern '${pattern}'` };\n }\n }\n }\n return { shouldBeDNT: false, reason: 'No DNT patterns matched' };\n}\n/**\n * Atomic Sanity types that should NOT be recursively flattened\n * These are terminal/leaf types that represent single values\n */\nconst ATOMIC_SANITY_TYPES = new Set([\n // Primitive-like types\n 'slug',\n 'date',\n 'datetime',\n // Reference types\n 'reference',\n // Asset types\n 'image',\n 'file',\n // Special content types\n 'geopoint',\n 'color',\n // Portable text building blocks (these are processed specially)\n 'block',\n 'span',\n]);\n/**\n * Build a GROQ-style path for field reconstruction\n *\n * @param documentContext - The document type and ID\n * @param fieldPath - The dotted field path (e.g., \"article.footnotes[_key == \\\"abc\\\"].footnote\")\n * @returns GROQ-style path like \"*[_type == \\\"blogPost\\\" && _id == $documentId][0].article.footnotes[_key == \\\"abc\\\"].footnote\"\n */\nfunction buildGroqPath(documentContext, fieldPath) {\n return `*[_type == \"${documentContext.documentType}\" && _id == $documentId][0].${fieldPath}`;\n}\nexport class ContentExtractor {\n /**\n * Infer the Sanity field type from a value\n *\n * @param value - The field value to inspect\n * @returns The inferred Sanity type string\n */\n inferSanityType(value) {\n if (value === null || value === undefined) {\n return 'undefined';\n }\n // Check for Sanity-specific object types\n if (typeof value === 'object' && !Array.isArray(value)) {\n const obj = value;\n // Sanity objects have a _type field\n if (obj._type) {\n return obj._type;\n }\n }\n // Check primitive types\n if (typeof value === 'string') {\n return 'string';\n }\n if (typeof value === 'number') {\n return 'number';\n }\n if (typeof value === 'boolean') {\n return 'boolean';\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n if (typeof value === 'object') {\n return 'object';\n }\n return 'unknown';\n }\n /**\n * Check if a value is an atomic Sanity type that should NOT be recursively flattened\n * These include types like slug, date, datetime, reference, image, file, etc.\n * Custom object types (e.g., articleInfo, footnoteInfo) are NOT atomic and should be flattened\n */\n isSanitySpecialType(value) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n const obj = value;\n // Only atomic Sanity types should be kept intact\n // Custom object types (anything with _type not in ATOMIC_SANITY_TYPES) should be flattened\n if (obj._type && ATOMIC_SANITY_TYPES.has(obj._type)) {\n return true;\n }\n return false;\n }\n /**\n * Check if an object should be recursively flattened into separate fields\n * Plain objects (fieldsets, custom object types without _type) should be flattened\n * Sanity special types should NOT be flattened\n */\n shouldFlattenObject(value) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n // Don't flatten Sanity special types (slug, date, reference, etc.)\n if (this.isSanitySpecialType(value)) {\n return false;\n }\n // Plain objects (fieldsets, custom objects) should be flattened\n return true;\n }\n /**\n * Recursively flatten a nested object into individual TranslatableField entries\n * Each leaf field gets its own entry with a dotted path key\n *\n * Arrays of objects with _key are flattened with key-based paths like:\n * article.footnotes[_key == \"abc123\"].footnote\n *\n * @param obj - The object to flatten\n * @param basePath - The base path prefix for keys\n * @param fields - The fields record to populate\n * @param docContext - Document context for GROQ path generation\n */\n flattenObjectToFields(obj, basePath, fields, docContext) {\n for (const [key, value] of Object.entries(obj)) {\n // Skip internal Sanity fields within nested objects\n if (key.startsWith('_')) {\n continue;\n }\n const fieldPath = basePath ? `${basePath}.${key}` : key;\n if (value === null || value === undefined) {\n continue;\n }\n // Handle arrays specially\n if (Array.isArray(value)) {\n this.flattenArrayToFields(value, fieldPath, key, fields, docContext);\n continue;\n }\n // Check if this is a custom object type that should be flattened\n // (objects with _type not in ATOMIC_SANITY_TYPES)\n if (typeof value === 'object' && value._type && !ATOMIC_SANITY_TYPES.has(value._type)) {\n // Recursively flatten custom object types\n this.flattenObjectToFields(value, fieldPath, fields, docContext);\n continue;\n }\n // Check if this is a nested plain object that should be further flattened\n if (this.shouldFlattenObject(value)) {\n // Recursively flatten nested objects\n this.flattenObjectToFields(value, fieldPath, fields, docContext);\n }\n else {\n // This is a leaf value (primitive or Sanity special type)\n this.addLeafField(key, value, fieldPath, fields, docContext);\n }\n }\n }\n /**\n * Flatten an array into individual TranslatableField entries\n * Arrays of objects with _key get key-based paths\n *\n * @param array - The array to flatten\n * @param fieldPath - The field path for this array\n * @param fieldName - The field name (last segment of path)\n * @param fields - The fields record to populate\n * @param docContext - Document context for GROQ path generation\n */\n flattenArrayToFields(array, fieldPath, fieldName, fields, docContext) {\n // Check if this is portable text (array of blocks)\n if (array.every(item => item && typeof item === 'object' && item._type === 'block')) {\n // Portable text - process as HTML and add as single field\n const extractedValue = this.processArray(fieldName, array);\n const fieldContext = {\n fieldPath,\n fieldName,\n fieldType: 'block'\n };\n const defaultDNT = computeDNTDefault(fieldContext);\n fields[fieldPath] = {\n value: extractedValue,\n dnt: defaultDNT.shouldBeDNT,\n type: 'block',\n path: buildGroqPath(docContext, fieldPath)\n };\n return;\n }\n // Check if this is an array of references (should be kept as-is)\n if (array.every(item => item && typeof item === 'object' && item._type === 'reference')) {\n fields[fieldPath] = {\n value: JSON.stringify(array),\n dnt: true, // References are always DNT\n type: 'array',\n path: buildGroqPath(docContext, fieldPath)\n };\n return;\n }\n // Check if this is an array of keyed objects that should be individually flattened\n const hasKeyedObjects = array.every(item => item && typeof item === 'object' && item._key);\n if (hasKeyedObjects) {\n // Flatten each keyed object with a key-based path\n for (const item of array) {\n const itemPath = `${fieldPath}[_key == \"${item._key}\"]`;\n // Check if this item has a _type (custom object type)\n if (item._type && !ATOMIC_SANITY_TYPES.has(item._type)) {\n // Recursively flatten the keyed object\n this.flattenObjectToFields(item, itemPath, fields, docContext);\n }\n else if (!item._type) {\n // Plain keyed object without _type - flatten its properties\n this.flattenObjectToFields(item, itemPath, fields, docContext);\n }\n else {\n // Atomic Sanity type - add as-is\n this.addLeafField(fieldName, item, itemPath, fields, docContext);\n }\n }\n return;\n }\n // For other arrays (primitives, mixed content, etc.), add as a single field\n const fieldContext = {\n fieldPath,\n fieldName,\n fieldType: 'array'\n };\n const defaultDNT = computeDNTDefault(fieldContext);\n fields[fieldPath] = {\n value: JSON.stringify(array),\n dnt: defaultDNT.shouldBeDNT,\n type: 'array',\n path: buildGroqPath(docContext, fieldPath)\n };\n }\n /**\n * Add a leaf field (primitive or atomic Sanity type) to the fields record\n */\n addLeafField(fieldName, value, fieldPath, fields, docContext) {\n let extractedValue;\n let fieldType;\n if (typeof value === 'object' && value !== null && '_type' in value && value._type === 'slug') {\n extractedValue = value.current || '';\n fieldType = 'slug';\n }\n else if (typeof value === 'object' && value !== null && '_type' in value && (value._type === 'date' || value._type === 'datetime')) {\n // For date/datetime, extract the value or serialize the object\n const dateValue = value.value || value;\n extractedValue = typeof dateValue === 'string' ? dateValue : JSON.stringify(dateValue);\n fieldType = value._type;\n }\n else if (typeof value === 'object') {\n // Serialize objects as JSON strings for the protobuf\n extractedValue = JSON.stringify(value);\n fieldType = this.inferSanityType(value);\n }\n else if (typeof value === 'string') {\n extractedValue = value;\n fieldType = 'string';\n }\n else {\n // For numbers, booleans, etc., convert to string\n extractedValue = String(value);\n fieldType = this.inferSanityType(value);\n }\n // Build field context for default DNT computation\n const fieldContext = {\n fieldPath,\n fieldName,\n fieldType\n };\n // Compute default DNT based on field context\n const defaultDNT = computeDNTDefault(fieldContext);\n // Add as TranslatableField with GROQ path\n fields[fieldPath] = {\n value: extractedValue,\n dnt: defaultDNT.shouldBeDNT,\n type: fieldType,\n path: buildGroqPath(docContext, fieldPath)\n };\n }\n /**\n * Extract content from a single Sanity document and convert to HTML\n */\n async extractDocumentContent(document) {\n if (!document || !document._id) {\n throw new Error('Invalid document provided');\n }\n const htmlContent = this.convertToHtml(document);\n return htmlContent;\n }\n /**\n * Convert Sanity document content to HTML format\n */\n convertToHtml(content) {\n if (!content) {\n return '';\n }\n let html = '';\n // Handle different field types\n for (const [key, value] of Object.entries(content)) {\n // Skip system fields\n if (key.startsWith('_')) {\n continue;\n }\n if (value) {\n html += this.processField(key, value);\n }\n }\n return html.trim();\n }\n /**\n * Extract structured content with separated body, title, slug, and fields\n * Also applies DNT preferences if DNT storage is provided\n *\n * @param document - The Sanity document to extract from\n * @param dntStorage - Optional DNT storage for applying user preferences\n */\n async extractStructuredContent(document, dntStorage) {\n if (!document || !document._id) {\n throw new Error('Invalid document provided');\n }\n const { title, foundAtTopLevel: titleFoundAtTopLevel } = this.extractTitle(document);\n const slug = this.extractSlug(document);\n const { bodyContent, fields, bodyFoundAtTopLevel, bodyFieldName } = this.separateContentAndFields(document);\n // DEBUG: Log extraction results\n console.log('[ContentExtractor] extractStructuredContent:', {\n documentId: document._id,\n documentType: document._type,\n extractedTitle: title,\n titleFoundAtTopLevel,\n bodyFoundAtTopLevel,\n bodyFieldName,\n documentHasTopLevelTitle: 'title' in document,\n documentHasTopLevelBody: 'body' in document || 'content' in document\n });\n // Apply DNT preferences from storage based on document type (if storage provided)\n const documentType = document._type || 'document';\n const enhancedFields = await this.applyDNTPreferences(documentType, fields, undefined, dntStorage);\n return {\n documentId: document._id,\n title,\n htmlContent: bodyContent,\n slug,\n fields: enhancedFields,\n titleFoundAtTopLevel,\n bodyFoundAtTopLevel,\n bodyFieldName\n };\n }\n /**\n * Apply DNT preferences to extracted fields based on document type\n * Now uses document-type-based configuration that applies to all documents of the same type\n *\n * DNT priority:\n * 1. Stored user preference (explicit override) - if dntStorage is provided\n * 2. Default based on field type (slug, date, datetime, reference, etc.)\n * 3. Default based on field name (containing \"author\" or \"contributor\")\n * 4. Default based on group/fieldset name (containing \"date\" or \"time\")\n * 5. Default to translatable (dnt: false)\n *\n * @param documentType - The document type\n * @param fields - The extracted fields\n * @param fieldContextMap - Optional context map for group/fieldset information\n * @param dntStorage - Optional DNT storage for retrieving user preferences\n */\n async applyDNTPreferences(documentType, fields, fieldContextMap, dntStorage) {\n try {\n // Get stored DNT field configuration for this document type (if storage provided)\n const storedDntFields = dntStorage\n ? await dntStorage.getFieldsForType(documentType)\n : {};\n // Apply DNT preferences to fields (fields already have type information from extraction)\n const enhancedFields = {};\n for (const [fieldPath, fieldValue] of Object.entries(fields)) {\n // Get the field name from the path\n const fieldName = fieldPath.split('.').pop() || fieldPath;\n // Get field type from the existing TranslatableField or infer it\n let fieldType;\n if (fieldValue && typeof fieldValue === 'object' && 'type' in fieldValue) {\n fieldType = fieldValue.type;\n }\n // Get group/fieldset context if available\n const context = fieldContextMap?.[fieldPath];\n // Build field context for DNT computation\n const fieldContext = {\n fieldPath,\n fieldName,\n fieldType,\n groupName: context?.groupName,\n fieldsetName: context?.fieldsetName\n };\n // Compute the default DNT status based on field context\n const defaultDNT = computeDNTDefault(fieldContext);\n // Check if there's a stored preference for this field (explicit user override)\n const hasStoredPreference = fieldPath in storedDntFields;\n // Determine effective DNT:\n // 1. Stored user preference (explicit override) takes highest priority\n // 2. If field was already marked dnt:true during extraction (e.g., reference arrays), preserve it\n // 3. Otherwise use computed default from field context\n const extractionDnt = (fieldValue && typeof fieldValue === 'object' && 'dnt' in fieldValue) ? fieldValue.dnt : undefined;\n const isDNT = hasStoredPreference\n ? storedDntFields[fieldPath]\n : (extractionDnt === true ? true : defaultDNT.shouldBeDNT);\n // Fields should already be in TranslatableField format with type set\n if (fieldValue && typeof fieldValue === 'object' && 'value' in fieldValue) {\n const typedField = fieldValue;\n enhancedFields[fieldPath] = {\n ...typedField,\n dnt: isDNT\n // type is already set from separateContentAndFields()\n };\n }\n else {\n // Fallback: if for some reason a field isn't wrapped yet, wrap it now\n enhancedFields[fieldPath] = {\n value: fieldValue,\n dnt: isDNT,\n type: this.inferSanityType(fieldValue)\n };\n }\n }\n return enhancedFields;\n }\n catch (error) {\n console.warn(`Failed to apply DNT preferences for document type ${documentType}:`, error);\n // Return original fields if preferences can't be loaded\n return fields;\n }\n }\n /**\n * Extract content from multiple documents for bulk operations\n */\n async extractBulkContent(documents) {\n const results = [];\n for (const document of documents) {\n try {\n const htmlContent = await this.extractDocumentContent(document);\n const { title } = this.extractTitle(document);\n results.push({\n documentId: document._id,\n title,\n htmlContent\n });\n }\n catch (error) {\n console.warn(`Failed to extract content from document ${document._id}:`, error);\n // Continue processing other documents\n }\n }\n return results;\n }\n /**\n * Extract structured content from multiple documents\n *\n * @param documents - Array of Sanity documents to extract from\n * @param dntStorage - Optional DNT storage for applying user preferences\n */\n async extractBulkStructuredContent(documents, dntStorage) {\n const results = [];\n for (const document of documents) {\n try {\n const structuredContent = await this.extractStructuredContent(document, dntStorage);\n results.push(structuredContent);\n }\n catch (error) {\n console.warn(`Failed to extract structured content from document ${document?._id || 'unknown'}:`, error);\n // Continue processing other documents\n }\n }\n return results;\n }\n /**\n * Process individual fields based on their type\n */\n processField(fieldName, fieldValue) {\n if (fieldValue === null || fieldValue === undefined) {\n return '';\n }\n // Handle arrays (like portable text blocks)\n if (Array.isArray(fieldValue)) {\n return this.processArray(fieldName, fieldValue);\n }\n // Handle objects\n if (typeof fieldValue === 'object') {\n return this.processObject(fieldName, fieldValue);\n }\n // Handle primitive values\n if (typeof fieldValue === 'string' || typeof fieldValue === 'number') {\n return this.wrapInHtml(fieldName, String(fieldValue));\n }\n return '';\n }\n /**\n * Process array fields (like portable text blocks)\n */\n processArray(fieldName, array) {\n let html = '';\n // Check if this is a list structure\n const isListArray = array.every(item => item && typeof item === 'object' && item._type === 'block' &&\n (item.listItem === 'bullet' || item.listItem === 'number'));\n if (isListArray) {\n // Handle as a list\n const listType = array[0]?.listItem === 'number' ? 'ol' : 'ul';\n html += `<${listType}>`;\n for (const item of array) {\n if (item._type === 'block') {\n const content = this.processPortableTextBlockContent(item);\n html += `<li>${content}</li>`;\n }\n }\n html += `</${listType}>`;\n }\n else {\n // Process as regular array\n for (const item of array) {\n if (item && typeof item === 'object') {\n // Handle portable text blocks\n if (item._type === 'block') {\n html += this.processPortableTextBlock(item);\n }\n else {\n // Handle other array items\n html += this.processObject(fieldName, item);\n }\n }\n else {\n // Handle primitive array items\n html += this.wrapInHtml('item', String(item));\n }\n }\n }\n return html;\n }\n /**\n * Process portable text blocks and convert to HTML\n */\n processPortableTextBlock(block) {\n const content = this.processPortableTextBlockContent(block);\n // Wrap in appropriate HTML tag based on block style\n const style = block.style || 'normal';\n switch (style) {\n case 'h1':\n return `<h1>${content}</h1>`;\n case 'h2':\n return `<h2>${content}</h2>`;\n case 'h3':\n return `<h3>${content}</h3>`;\n case 'h4':\n return `<h4>${content}</h4>`;\n case 'h5':\n return `<h5>${content}</h5>`;\n case 'h6':\n return `<h6>${content}</h6>`;\n case 'blockquote':\n return `<blockquote>${content}</blockquote>`;\n default:\n return `<p>${content}</p>`;\n }\n }\n /**\n * Extract content from portable text block children\n */\n processPortableTextBlockContent(block) {\n if (!block.children || !Array.isArray(block.children)) {\n return '';\n }\n let content = '';\n // Extract text from children\n for (const child of block.children) {\n if (child._type === 'span' && child.text) {\n let text = child.text;\n // Apply formatting marks\n if (child.marks && Array.isArray(child.marks)) {\n for (const mark of child.marks) {\n if (typeof mark === 'string') {\n // Simple marks\n switch (mark) {\n case 'strong':\n text = `<strong>${text}</strong>`;\n break;\n case 'em':\n text = `<em>${text}</em>`;\n break;\n case 'underline':\n text = `<u>${text}</u>`;\n break;\n case 'code':\n text = `<code>${text}</code>`;\n break;\n }\n }\n else if (typeof mark === 'object' && mark._type === 'link') {\n // Link annotations\n const href = mark.href || '#';\n text = `<a href=\"${this.escapeHtml(href)}\">${text}</a>`;\n }\n }\n }\n content += text;\n }\n }\n return content;\n }\n /**\n * Process object fields\n */\n processObject(fieldName, obj) {\n let html = '';\n // Handle references\n if (obj._type === 'reference' && obj._ref) {\n return `<span data-reference=\"${obj._ref}\">Referenced content</span>`;\n }\n // Handle images\n if (obj._type === 'image') {\n const alt = obj.alt || 'Image';\n const caption = obj.caption || '';\n return `<figure><img alt=\"${this.escapeHtml(alt)}\" />${caption ? `<figcaption>${this.escapeHtml(caption)}</figcaption>` : ''}</figure>`;\n }\n // Handle files\n if (obj._type === 'file') {\n const title = obj.title || 'File';\n return `<a href=\"#\" data-file-ref=\"${obj.asset?._ref || ''}\">${this.escapeHtml(title)}</a>`;\n }\n // Handle URLs\n if (obj._type === 'url') {\n const href = obj.href || '#';\n const text = obj.text || href;\n return `<a href=\"${this.escapeHtml(href)}\">${this.escapeHtml(text)}</a>`;\n }\n // Handle geopoints\n if (obj._type === 'geopoint') {\n const lat = obj.lat || 0;\n const lng = obj.lng || 0;\n const alt = obj.alt || '';\n return `<span data-geopoint data-lat=\"${lat}\" data-lng=\"${lng}\" ${alt ? `data-alt=\"${alt}\"` : ''}>Location: ${lat}, ${lng}</span>`;\n }\n // Handle slugs\n if (obj._type === 'slug') {\n const current = obj.current || '';\n return `<span data-slug=\"${this.escapeHtml(current)}\">${this.escapeHtml(current)}</span>`;\n }\n // Handle dates\n if (obj._type === 'date' || obj._type === 'datetime') {\n const dateValue = obj.value || obj;\n if (typeof dateValue === 'string') {\n const date = new Date(dateValue);\n return `<time datetime=\"${dateValue}\">${date.toLocaleDateString()}</time>`;\n }\n }\n // Handle color objects\n if (obj._type === 'color') {\n const hex = obj.hex || '#000000';\n const alpha = obj.alpha !== undefined ? obj.alpha : 1;\n return `<span data-color=\"${hex}\" data-alpha=\"${alpha}\" style=\"color: ${hex}\">Color: ${hex}</span>`;\n }\n // Handle spans with annotations (links, etc.)\n if (obj._type === 'span' && obj.marks && Array.isArray(obj.marks)) {\n let text = obj.text || '';\n // Apply formatting marks\n for (const mark of obj.marks) {\n if (typeof mark === 'string') {\n // Simple marks like 'strong', 'em', etc.\n switch (mark) {\n case 'strong':\n text = `<strong>${text}</strong>`;\n break;\n case 'em':\n text = `<em>${text}</em>`;\n break;\n case 'underline':\n text = `<u>${text}</u>`;\n break;\n case 'code':\n text = `<code>${text}</code>`;\n break;\n }\n }\n else if (typeof mark === 'object' && mark._type === 'link') {\n // Link annotations\n const href = mark.href || '#';\n text = `<a href=\"${this.escapeHtml(href)}\">${text}</a>`;\n }\n }\n return text;\n }\n // Handle other objects recursively\n for (const [key, value] of Object.entries(obj)) {\n if (!key.startsWith('_') && value) {\n html += this.processField(key, value);\n }\n }\n return html;\n }\n /**\n * Wrap content in HTML with field name as class\n */\n wrapInHtml(fieldName, content) {\n const safeFieldName = fieldName.replace(/[^a-zA-Z0-9-_]/g, '');\n return `<div class=\"field-${safeFieldName}\">${this.escapeHtml(content)}</div>`;\n }\n /**\n * Separate main content from metadata fields\n * All fields are immediately wrapped in TranslatableField format with type information\n * DNT defaults are computed based on field type and name patterns\n *\n * Complex types (objects/fieldsets) are recursively flattened into individual fields\n * using dotted path notation (e.g., \"metadata.version\", \"metadata.status\")\n */\n separateContentAndFields(document) {\n const contentFields = ['body', 'content'];\n const metadataFields = ['title', 'slug', '_id', '_type', '_createdAt', '_updatedAt', '_rev'];\n let bodyContent = '';\n let bodyFoundAtTopLevel = false;\n let bodyFieldName;\n const fields = {};\n // Create document context for GROQ path generation\n const docContext = {\n documentType: document._type || 'document',\n documentId: document._id\n };\n // First, try to find body content at top level\n for (const [key, value] of Object.entries(document)) {\n // Skip system fields\n if (key.startsWith('_')) {\n continue;\n }\n // Skip title and slug as they're handled separately\n if (key === 'title' || key === 'slug') {\n continue;\n }\n if (value) {\n // Check if this is a main content field at top level\n if (contentFields.includes(key)) {\n bodyContent += this.processField(key, value);\n bodyFoundAtTopLevel = true;\n bodyFieldName = key;\n }\n else {\n // Handle arrays specially\n if (Array.isArray(value)) {\n this.flattenArrayToFields(value, key, key, fields, docContext);\n }\n // Check if this is a custom object type that should be flattened\n else if (typeof value === 'object' && value._type && !ATOMIC_SANITY_TYPES.has(value._type)) {\n // Recursively flatten custom object types (e.g., articleInfo)\n this.flattenObjectToFields(value, key, fields, docContext);\n }\n // Check if this is a plain object that should be recursively flattened\n else if (this.shouldFlattenObject(value)) {\n // Recursively flatten nested objects into individual fields with dotted paths\n this.flattenObjectToFields(value, key, fields, docContext);\n }\n else {\n // Add to fields as TranslatableField with type information\n this.addLeafField(key, value, key, fields, docContext);\n }\n }\n }\n }\n // If no main content found at top level, search in nested fields\n if (!bodyContent.trim()) {\n const nestedBody = this.findBodyInNestedFields(document, contentFields);\n if (nestedBody) {\n bodyContent = nestedBody.content;\n bodyFoundAtTopLevel = false;\n bodyFieldName = nestedBody.fieldPath;\n }\n }\n // If still no content found, fall back to processing all non-metadata fields\n if (!bodyContent.trim()) {\n for (const [key, value] of Object.entries(document)) {\n if (!key.startsWith('_') && !metadataFields.includes(key) && value) {\n bodyContent += this.processField(key, value);\n }\n }\n // This is a fallback, not a specific body field\n bodyFoundAtTopLevel = false;\n bodyFieldName = undefined;\n }\n return { bodyContent: bodyContent.trim(), fields, bodyFoundAtTopLevel, bodyFieldName };\n }\n /**\n * Recursively search nested objects and fieldsets for a body/content field\n */\n findBodyInNestedFields(obj, contentFields, basePath = '') {\n for (const [key, value] of Object.entries(obj)) {\n // Skip system/internal fields\n if (key.startsWith('_')) {\n continue;\n }\n if (value === null || value === undefined) {\n continue;\n }\n const fieldPath = basePath ? `${basePath}.${key}` : key;\n // Check if this nested object contains a body field\n if (typeof value === 'object' && !Array.isArray(value)) {\n // Skip atomic Sanity types (slug, reference, image, etc.)\n if (this.isSanitySpecialType(value)) {\n continue;\n }\n // Check if this nested object has a body field directly\n for (const contentField of contentFields) {\n if (value[contentField]) {\n const nestedPath = `${fieldPath}.${contentField}`;\n const content = this.processField(contentField, value[contentField]);\n if (content.trim()) {\n return { content, fieldPath: nestedPath };\n }\n }\n }\n // Recursively search deeper\n const found = this.findBodyInNestedFields(value, contentFields, fieldPath);\n if (found) {\n return found;\n }\n }\n // Also search within arrays of keyed objects\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item && typeof item === 'object' && !this.isSanitySpecialType(item)) {\n // Check if this array item has a body field\n for (const contentField of contentFields) {\n if (item[contentField]) {\n const itemPath = item._key\n ? `${fieldPath}[_key == \"${item._key}\"].${contentField}`\n : `${fieldPath}.${contentField}`;\n const content = this.processField(contentField, item[contentField]);\n if (content.trim()) {\n return { content, fieldPath: itemPath };\n }\n }\n }\n // Recursively search deeper in the array item\n const itemBasePath = item._key\n ? `${fieldPath}[_key == \"${item._key}\"]`\n : fieldPath;\n const found = this.findBodyInNestedFields(item, contentFields, itemBasePath);\n if (found) {\n return found;\n }\n }\n }\n }\n }\n return null;\n }\n /**\n * Extract slug from document\n */\n extractSlug(document) {\n // Check for slug field\n if (document.slug) {\n if (typeof document.slug === 'object' && document.slug !== null && '_type' in document.slug && document.slug._type === 'slug') {\n return document.slug.current || '';\n }\n if (typeof document.slug === 'string') {\n return document.slug;\n }\n }\n // Check for other slug-like fields\n const slugFields = ['slug', 'path', 'url', 'permalink'];\n for (const field of slugFields) {\n if (document[field]) {\n if (typeof document[field] === 'object' && document[field] !== null && '_type' in document[field] && document[field]._type === 'slug') {\n return document[field].current || '';\n }\n if (typeof document[field] === 'string') {\n return document[field];\n }\n }\n }\n return '';\n }\n /**\n * Extract title from document\n * Searches top-level fields first, then descends into nested objects/fieldsets\n * @returns Object with title string and flag indicating if found at top level\n */\n extractTitle(document) {\n const titleFields = ['title', 'name', 'heading', 'label'];\n // First, try top-level fields\n for (const field of titleFields) {\n if (document[field] && typeof document[field] === 'string') {\n return { title: document[field], foundAtTopLevel: true };\n }\n }\n // If not found at top level, search nested objects/fieldsets\n const nestedTitle = this.findTitleInNestedFields(document, titleFields);\n if (nestedTitle) {\n return { title: nestedTitle, foundAtTopLevel: false };\n }\n // Fallback to document type and ID\n return { title: `${document._type} (${document._id})`, foundAtTopLevel: false };\n }\n /**\n * Recursively search nested objects and fieldsets for a title field\n */\n findTitleInNestedFields(obj, titleFields) {\n for (const [key, value] of Object.entries(obj)) {\n // Skip system/internal fields\n if (key.startsWith('_')) {\n continue;\n }\n if (value === null || value === undefined) {\n continue;\n }\n // Check if this nested object contains a title field\n if (typeof value === 'object' && !Array.isArray(value)) {\n // Skip atomic Sanity types (slug, reference, image, etc.)\n if (this.isSanitySpecialType(value)) {\n continue;\n }\n // Check if this nested object has a title field directly\n for (const titleField of titleFields) {\n if (value[titleField] && typeof value[titleField] === 'string') {\n return value[titleField];\n }\n }\n // Recursively search deeper\n const found = this.findTitleInNestedFields(value, titleFields);\n if (found) {\n return found;\n }\n }\n // Also search within arrays of keyed objects (like fieldsets containing objects)\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item && typeof item === 'object' && !this.isSanitySpecialType(item)) {\n // Check if this array item has a title field\n for (const titleField of titleFields) {\n if (item[titleField] && typeof item[titleField] === 'string') {\n return item[titleField];\n }\n }\n // Recursively search deeper in the array item\n const found = this.findTitleInNestedFields(item, titleFields);\n if (found) {\n return found;\n }\n }\n }\n }\n }\n return null;\n }\n /**\n * Escape HTML special characters\n */\n escapeHtml(text) {\n const htmlEscapeMap = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;'\n };\n return text.replace(/[&<>\"']/g, (char) => htmlEscapeMap[char]);\n }\n}\n//# sourceMappingURL=contentExtractor.js.map","import * as TranslationRequestProto from '@easyling/protos-sanity/dist/generated/translation_request';\nimport * as TranslationResponseProto from '@easyling/protos-sanity/dist/generated/translation_response';\nexport class TranslationService {\n constructor(placeholderEndpoint = 'http://localhost:8275/translate', requestContentType = 'application/json', responseAcceptHeader = 'application/json') {\n this.placeholderEndpoint = placeholderEndpoint;\n this.requestContentType = requestContentType;\n this.responseAcceptHeader = responseAcceptHeader;\n }\n /**\n * Infer the Sanity field type from a value\n *\n * @param value - The field value to inspect\n * @returns The inferred Sanity type string\n */\n inferSanityType(value) {\n if (value === null || value === undefined) {\n return 'undefined';\n }\n // Check for Sanity-specific object types\n if (typeof value === 'object' && !Array.isArray(value)) {\n const obj = value;\n // Sanity objects have a _type field\n if (obj._type) {\n return obj._type;\n }\n }\n // Check primitive types\n if (typeof value === 'string') {\n return 'string';\n }\n if (typeof value === 'number') {\n return 'number';\n }\n if (typeof value === 'boolean') {\n return 'boolean';\n }\n if (Array.isArray(value)) {\n return 'array';\n }\n if (typeof value === 'object') {\n return 'object';\n }\n return 'unknown';\n }\n /**\n * Set authentication token and project ID\n * Requirements: 4.1, 4.2, 4.3\n *\n * @param token - Access token for API authentication\n * @param projectId - Project ID to include in requests\n */\n setAuthToken(token, projectId) {\n this.accessToken = token;\n this.projectId = projectId;\n }\n /**\n * Clear authentication data\n */\n clearAuth() {\n this.accessToken = undefined;\n this.projectId = undefined;\n }\n /**\n * Update configuration for content types and endpoint\n * Allows partial updates - only provided parameters will be updated\n * Requirements: 1.1, 2.3, 3.3\n *\n * @param endpoint - Optional translation API endpoint URL\n * @param requestContentType - Optional request Content-Type header value\n * @param responseAcceptHeader - Optional response Accept header value\n */\n setConfiguration(endpoint, requestContentType, responseAcceptHeader) {\n if (endpoint !== undefined) {\n this.placeholderEndpoint = endpoint;\n }\n if (requestContentType !== undefined) {\n this.requestContentType = requestContentType;\n }\n if (responseAcceptHeader !== undefined) {\n this.responseAcceptHeader = responseAcceptHeader;\n }\n }\n /**\n * Convert internal payload to Protocol Buffer binary format\n * Requirements: Uses @easyling/sanity protobuf library\n *\n * @param payload - Internal translation request payload\n * @returns Binary protobuf message\n */\n convertPayloadToProtobuf(payload) {\n // Convert internal TranslatableField objects to protobuf format\n // Type information should be set by this point (from contentExtractor)\n const protoFields = {};\n for (const [key, field] of Object.entries(payload.content.fields)) {\n // Handle both TranslatableField objects and plain values (for backward compatibility)\n if (field && typeof field === 'object' && 'value' in field) {\n // Already a TranslatableField object - type should be set from contentExtractor\n const typedField = field;\n // Warn if type is missing - should be set by contentExtractor in normal flow\n let fieldType = typedField.type;\n if (!fieldType) {\n console.warn(`Field '${key}' missing type in protobuf conversion, inferring from value`);\n fieldType = this.inferSanityType(typedField.value);\n }\n protoFields[key] = {\n value: typeof typedField.value === 'string' ? typedField.value : JSON.stringify(typedField.value),\n dnt: typedField.dnt || false,\n type: fieldType,\n path: typedField.path ?? key\n };\n }\n else {\n // Plain value - may happen for direct API calls that bypass contentExtractor\n console.warn(`Field '${key}' not in TranslatableField format, wrapping with inferred type`);\n protoFields[key] = {\n value: typeof field === 'string' ? field : JSON.stringify(field),\n dnt: false,\n type: this.inferSanityType(field),\n path: key\n };\n }\n }\n // Create protobuf message from our payload\n const protoPayload = TranslationRequestProto.TranslationRequestPayload.create({\n content: {\n body: payload.content.body,\n title: payload.content.title,\n slug: payload.content.slug,\n fields: protoFields\n },\n project: this.projectId || '', // Project code for identification\n format: payload.format,\n metadata: {\n documentId: payload.metadata.documentId,\n documentType: payload.metadata.documentType,\n title: payload.metadata.title,\n sourceLanguage: payload.metadata.sourceLanguage || '',\n targetLanguage: payload.metadata.targetLanguage || '',\n targetLocales: payload.metadata.targetLocales || []\n }\n });\n // Encode protobuf message to binary format\n return TranslationRequestProto.TranslationRequestPayload.encode(protoPayload).finish();\n }\n /**\n * Convert protobuf payload to JSON for logging purposes only\n *\n * @param payload - Internal translation request payload\n * @returns JSON representation for logging\n */\n convertPayloadToProtobufJSON(payload) {\n // Convert internal TranslatableField objects to protobuf format\n const protoFields = {};\n for (const [key, field] of Object.entries(payload.content.fields)) {\n if (field && typeof field === 'object' && 'value' in field) {\n const typedField = field;\n protoFields[key] = {\n value: typeof typedField.value === 'string' ? typedField.value : JSON.stringify(typedField.value),\n dnt: typedField.dnt || false,\n type: typedField.type || 'unknown',\n path: typedField.path ?? key\n };\n }\n else {\n protoFields[key] = {\n value: typeof field === 'string' ? field : JSON.stringify(field),\n dnt: false,\n type: 'unknown',\n path: key\n };\n }\n }\n const protoPayload = TranslationRequestProto.TranslationRequestPayload.create({\n content: {\n body: payload.content.body,\n title: payload.content.title,\n slug: payload.content.slug,\n fields: protoFields\n },\n project: this.projectId || '',\n format: payload.format,\n metadata: {\n documentId: payload.metadata.documentId,\n documentType: payload.metadata.documentType,\n title: payload.metadata.title,\n sourceLanguage: payload.metadata.sourceLanguage || '',\n targetLanguage: payload.metadata.targetLanguage || '',\n targetLocales: payload.metadata.targetLocales || []\n }\n });\n return TranslationRequestProto.TranslationRequestPayload.toJSON(protoPayload);\n }\n /**\n * Normalize field values to ensure consistency\n * Extracts values from TranslatableField objects and handles various formats\n */\n normalizeTranslatedFields(fields) {\n const normalizedFields = {};\n if (!fields || typeof fields !== 'object') {\n return normalizedFields;\n }\n for (const [key, fieldValue] of Object.entries(fields)) {\n // Handle both TranslatableField objects and plain values\n if (fieldValue && typeof fieldValue === 'object' && 'value' in fieldValue) {\n // It's already a TranslatableField object\n normalizedFields[key] = {\n value: fieldValue.value,\n dnt: fieldValue.dnt || false,\n type: fieldValue.type || this.inferSanityType(fieldValue.value)\n };\n }\n else {\n // It's a plain value - wrap it in TranslatableField format\n normalizedFields[key] = {\n value: fieldValue,\n dnt: false,\n type: this.inferSanityType(fieldValue)\n };\n }\n }\n return normalizedFields;\n }\n /**\n * Convert binary protobuf response to internal format\n * Requirements: Uses @easyling/sanity protobuf library\n *\n * @param binaryData - Binary protobuf response data\n * @returns Internal translation response format\n */\n convertProtobufBinaryToResponse(binaryData) {\n // Decode binary protobuf response\n const protoResponse = TranslationResponseProto.TranslationResponse.decode(binaryData);\n // Convert to internal format\n const translatedDocuments = protoResponse.translatedDocuments.map(doc => {\n // Convert protobuf TranslatableField back to internal format\n const fields = {};\n if (doc.fields && typeof doc.fields === 'object') {\n for (const [key, protoField] of Object.entries(doc.fields)) {\n if (protoField && typeof protoField === 'object' && 'value' in protoField) {\n const fieldValue = protoField.value;\n const fieldType = protoField.type;\n try {\n // Try to parse as JSON if it's a stringified value\n const parsedValue = JSON.parse(fieldValue);\n fields[key] = {\n value: parsedValue,\n dnt: protoField.dnt || false,\n type: fieldType || this.inferSanityType(parsedValue)\n };\n }\n catch {\n // If parsing fails, use the string value as-is\n fields[key] = {\n value: fieldValue,\n dnt: protoField.dnt || false,\n type: fieldType || this.inferSanityType(fieldValue)\n };\n }\n }\n }\n }\n return {\n body: doc.body,\n title: doc.title,\n slug: doc.slug,\n fields,\n locale: doc.locale\n };\n });\n return {\n success: protoResponse.success,\n translatedDocuments,\n sourceLocale: protoResponse.sourceLocale,\n error: protoResponse.error,\n requestId: protoResponse.requestId\n };\n }\n /**\n * Convert protobuf JSON response back to internal format (for legacy support)\n * Requirements: Uses @easyling/sanity protobuf library\n *\n * @param jsonData - JSON response data\n * @returns Internal translation response format\n */\n convertProtobufJSONToResponse(jsonData) {\n // Parse the JSON into a protobuf message\n const protoResponse = TranslationResponseProto.TranslationResponse.fromJSON(jsonData);\n // Convert to internal format\n const translatedDocuments = protoResponse.translatedDocuments.map((doc, index) => {\n // Get original document data from jsonData to handle mixed field formats\n const originalDoc = jsonData.translatedDocuments?.[index];\n // Convert protobuf TranslatableField back to internal format\n const protoFields = {};\n if (doc.fields && typeof doc.fields === 'object') {\n for (const [key, protoField] of Object.entries(doc.fields)) {\n // Get the original value from jsonData to check if protobuf lost it\n const originalValue = originalDoc?.fields?.[key];\n // Handle protobuf field format\n if (protoField && typeof protoField === 'object' && 'value' in protoField) {\n const fieldValue = protoField.value;\n const fieldType = protoField.type;\n // Check if protobuf parsing lost the value (empty string when original had value)\n if ((fieldValue === '' || fieldValue === undefined) && originalValue !== undefined && originalValue !== '') {\n // Use original value instead\n protoFields[key] = originalValue;\n }\n else {\n try {\n // Try to parse as JSON if it's a stringified value\n const parsedValue = JSON.parse(fieldValue);\n protoFields[key] = {\n value: parsedValue,\n dnt: protoField.dnt || false,\n type: fieldType || this.inferSanityType(parsedValue)\n };\n }\n catch {\n // If parsing fails, use the string value as-is\n protoFields[key] = {\n value: fieldValue,\n dnt: protoField.dnt || false,\n type: fieldType || this.inferSanityType(fieldValue)\n };\n }\n }\n }\n else {\n // Plain value - but protobuf parsing might have lost it\n // Fall back to original JSON data if the value is empty/undefined\n if (originalValue !== undefined && (!protoField || protoField === '')) {\n protoFields[key] = originalValue;\n }\n else {\n protoFields[key] = protoField;\n }\n }\n }\n }\n // Also check for fields in original data that might have been lost in protobuf conversion\n if (originalDoc?.fields && typeof originalDoc.fields === 'object') {\n for (const [key, originalValue] of Object.entries(originalDoc.fields)) {\n if (!(key in protoFields)) {\n protoFields[key] = originalValue;\n }\n }\n }\n // Normalize the fields to ensure consistent format\n const fields = this.normalizeTranslatedFields(protoFields);\n return {\n body: doc.body,\n title: doc.title,\n slug: doc.slug,\n fields,\n locale: doc.locale\n };\n });\n return {\n success: protoResponse.success,\n translatedDocuments,\n sourceLocale: protoResponse.sourceLocale,\n error: protoResponse.error,\n requestId: protoResponse.requestId\n };\n }\n /**\n * Prepare a translation request for a single document\n * Requirements: 1.2, 1.3, 3.3, 2.5, 2.7\n *\n * @param content - Document content to translate\n * @param documentType - Type of the document\n * @param sourceLanguage - Source language code (optional)\n * @param targetLanguage - Single target language code (optional, for backward compatibility)\n * @param targetLocales - Array of target locale codes (optional, for multi-locale support)\n */\n prepareTranslationRequest(content, documentType = 'document', sourceLanguage, targetLanguage, targetLocales) {\n if (!content || !content.documentId || !content.htmlContent) {\n throw new Error('Invalid document content provided');\n }\n // Convert flat fields to TranslatableField objects and ensure type is ALWAYS set\n const translatableFields = {};\n if (content.fields) {\n for (const [key, value] of Object.entries(content.fields)) {\n // If the field is already in the new format, ensure type is set\n if (value && typeof value === 'object' && 'value' in value) {\n const typedField = value;\n // Type should already be set from contentExtractor, but ensure it's never undefined\n if (!typedField.type) {\n console.warn(`Field '${key}' missing type, inferring from value`);\n }\n translatableFields[key] = {\n ...typedField,\n type: typedField.type || this.inferSanityType(typedField.value)\n };\n }\n else {\n // Convert flat field to TranslatableField object (should rarely happen)\n console.warn(`Field '${key}' not in TranslatableField format, converting`);\n translatableFields[key] = {\n value,\n dnt: false,\n type: this.inferSanityType(value)\n };\n }\n }\n }\n // DEBUG: Log titleFoundAtTopLevel from content\n console.log('[TranslationService] prepareTranslationRequest - titleFoundAtTopLevel:', {\n fromContent: content.titleFoundAtTopLevel,\n willUse: content.titleFoundAtTopLevel ?? true\n });\n const payload = {\n content: {\n body: content.htmlContent,\n title: content.title || `Document ${content.documentId}`,\n slug: content.slug || '',\n fields: translatableFields\n },\n format: 'html',\n metadata: {\n documentId: content.documentId,\n documentType,\n title: content.title || `Document ${content.documentId}`,\n ...(sourceLanguage && { sourceLanguage }),\n // Support both single targetLanguage (backward compatibility) and targetLocales array\n ...(targetLanguage && { targetLanguage }),\n ...(targetLocales && targetLocales.length > 0 && { targetLocales }),\n // Track whether title was found at top level for document creation\n titleFoundAtTopLevel: content.titleFoundAtTopLevel ?? true\n }\n };\n return {\n documentId: content.documentId,\n endpoint: this.placeholderEndpoint,\n payload\n };\n }\n /**\n * Translate a single document\n * Requirements: 1.2, 1.3, 3.3, 2.5, 2.7\n *\n * @param content - Document content to translate\n * @param documentType - Type of the document\n * @param sourceLanguage - Source language code (optional)\n * @param targetLanguage - Single target language code (optional, for backward compatibility)\n * @param targetLocales - Array of target locale codes (optional, for multi-locale support)\n */\n async translateDocument(content, documentType = 'document', sourceLanguage, targetLanguage, targetLocales) {\n const request = this.prepareTranslationRequest(content, documentType, sourceLanguage, targetLanguage, targetLocales);\n return this.sendTranslationRequest(request);\n }\n /**\n * Send translation request to the configured endpoint\n *\n * Uses the @easyling/sanity Protocol Buffer library to format messages as JSON\n * (not binary protobuf) for better compatibility with various backends.\n * Handles the new array-based response format with backward compatibility.\n * The service now expects translatedDocuments as an array, but will convert\n * legacy formats (translatedContent or translations object) to the new format.\n *\n * Supports dual mode operation:\n * - Authenticated mode: Uses Bearer token authentication when configured\n * - Legacy mode: Works without authentication for backward compatibility\n */\n async sendTranslationRequest(request) {\n try {\n this.logTranslationRequest(request);\n // Build headers with configured content types\n // Requirements: 2.2, 2.3, 3.2, 3.3\n const headers = {\n 'Content-Type': this.requestContentType,\n 'Accept': this.responseAcceptHeader\n };\n // Add Authorization header if access token is available\n if (this.accessToken) {\n headers['Authorization'] = `Bearer ${this.accessToken}`;\n }\n // Serialize payload based on configured content type\n // Requirements: 2.2, 2.3\n let body;\n if (this.requestContentType === 'application/x-protobuf') {\n // Use binary protobuf serialization\n body = this.convertPayloadToProtobuf(request.payload);\n }\n else {\n // Use JSON serialization (protobuf JSON format)\n const protobufJSON = this.convertPayloadToProtobufJSON(request.payload);\n body = JSON.stringify(protobufJSON);\n }\n const response = await fetch(request.endpoint, {\n method: 'POST',\n headers,\n body: body // TypeScript fetch types are strict, but Uint8Array is valid\n });\n if (!response.ok) {\n // Handle 401 Unauthorized\n if (response.status === 401) {\n return {\n success: false,\n error: 'Authentication failed. Please check your access token in the Easyling Configuration.'\n };\n }\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n // Parse response based on configured Accept header\n // Requirements: 3.2, 3.3, 3.5\n if (this.responseAcceptHeader === 'application/x-protobuf') {\n // Parse binary protobuf response\n const arrayBuffer = await response.arrayBuffer();\n const binaryData = new Uint8Array(arrayBuffer);\n return this.convertProtobufBinaryToResponse(binaryData);\n }\n // Parse JSON response\n const data = await response.json();\n // Try to parse as protobuf JSON format first\n try {\n // If the response has the expected protobuf structure, parse it\n if (data.success !== undefined && (data.translatedDocuments || data.error)) {\n return this.convertProtobufJSONToResponse(data);\n }\n }\n catch (protoError) {\n console.warn('Failed to parse response as protobuf format, falling back to legacy handling:', protoError);\n }\n // New format: translatedDocuments array (without success field - for backward compatibility)\n if (data.translatedDocuments && Array.isArray(data.translatedDocuments)) {\n // Normalize fields in each translated document to ensure consistency\n const normalizedDocuments = data.translatedDocuments.map((doc) => ({\n ...doc,\n fields: this.normalizeTranslatedFields(doc.fields || {})\n }));\n return {\n success: true,\n translatedDocuments: normalizedDocuments,\n sourceLocale: data.sourceLocale,\n requestId: data.requestId\n };\n }\n // Backward compatibility: translations object (convert to array)\n if (data.translations) {\n const translatedDocuments = [];\n for (const [locale, translation] of Object.entries(data.translations)) {\n if (translation && typeof translation === 'object' && 'content' in translation) {\n const content = translation.content;\n // Normalize fields to ensure consistency\n translatedDocuments.push({\n ...content,\n fields: this.normalizeTranslatedFields(content.fields || {}),\n locale\n });\n }\n }\n return {\n success: true,\n translatedDocuments,\n sourceLocale: data.sourceLocale,\n requestId: data.requestId,\n // Keep deprecated field for backward compatibility\n translations: data.translations\n };\n }\n // Backward compatibility: single translatedContent object (convert to array)\n if (data.translatedContent) {\n const targetLocale = request.payload.metadata.targetLanguage ||\n request.payload.metadata.targetLocales?.[0];\n // Normalize fields to ensure consistency\n const normalizedContent = {\n ...data.translatedContent,\n fields: this.normalizeTranslatedFields(data.translatedContent.fields || {}),\n locale: targetLocale\n };\n return {\n success: true,\n translatedDocuments: [normalizedContent],\n sourceLocale: request.payload.metadata.sourceLanguage,\n requestId: data.requestId,\n // Keep deprecated field for backward compatibility\n translatedContent: data.translatedContent\n };\n }\n // Fallback: treat data.content as translatedContent\n if (data.content) {\n const targetLocale = request.payload.metadata.targetLanguage ||\n request.payload.metadata.targetLocales?.[0];\n // Normalize fields to ensure consistency\n const normalizedContent = {\n ...data.content,\n fields: this.normalizeTranslatedFields(data.content.fields || {}),\n locale: targetLocale\n };\n return {\n success: true,\n translatedDocuments: [normalizedContent],\n sourceLocale: request.payload.metadata.sourceLanguage,\n requestId: data.requestId,\n // Keep deprecated field for backward compatibility\n translatedContent: data.content\n };\n }\n throw new Error('Invalid response format: missing translatedDocuments, translations, or translatedContent');\n }\n catch (error) {\n console.error(`Translation request failed for document ${request.documentId}:`, error);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n /**\n * Log translation request to console for verification\n * Requirements: 1.3, 2.4\n */\n logTranslationRequest(request) {\n console.log('Translation Request:', {\n timestamp: new Date().toISOString(),\n documentId: request.documentId,\n endpoint: request.endpoint,\n payload: request.payload\n });\n }\n /**\n * Process bulk translation for multiple documents\n * Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 2.7\n *\n * @param contents - Array of document contents to translate\n * @param documentType - Type of the documents\n * @param sourceLanguage - Source language code (optional)\n * @param targetLanguage - Single target language code (optional, for backward compatibility)\n * @param targetLocales - Array of target locale codes (optional, for multi-locale support)\n */\n async processBulkTranslation(contents, documentType = 'document', sourceLanguage, targetLanguage, targetLocales) {\n const summary = {\n totalDocuments: contents.length,\n processedDocuments: 0,\n failedDocuments: 0,\n requests: [],\n responses: []\n };\n const localeCount = targetLocales?.length || 1;\n console.log(`Starting bulk translation for ${contents.length} documents to ${localeCount} locale(s)`);\n for (const content of contents) {\n try {\n // Prepare translation request for each document\n const request = this.prepareTranslationRequest(content, documentType, sourceLanguage, targetLanguage, targetLocales);\n // Send the translation request\n const response = await this.sendTranslationRequest(request);\n // Add to summary\n summary.requests.push(request);\n summary.responses.push(response);\n if (response.success) {\n summary.processedDocuments++;\n }\n else {\n summary.failedDocuments++;\n }\n }\n catch (error) {\n console.error(`Failed to process document ${content.documentId}:`, error);\n summary.failedDocuments++;\n summary.responses.push({\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n });\n }\n }\n // Log bulk operation summary\n this.logBulkTranslationSummary(summary);\n return summary;\n }\n /**\n * Log bulk translation summary\n * Requirements: 2.5\n */\n logBulkTranslationSummary(summary) {\n console.log('Bulk Translation Summary:', {\n timestamp: new Date().toISOString(),\n totalDocuments: summary.totalDocuments,\n processedDocuments: summary.processedDocuments,\n failedDocuments: summary.failedDocuments,\n successRate: summary.totalDocuments > 0\n ? ((summary.processedDocuments / summary.totalDocuments) * 100).toFixed(2) + '%'\n : '0%'\n });\n }\n /**\n * Update the placeholder endpoint\n */\n setEndpoint(endpoint) {\n this.placeholderEndpoint = endpoint;\n }\n /**\n * Get the current endpoint\n */\n getEndpoint() {\n return this.placeholderEndpoint;\n }\n}\n//# sourceMappingURL=translationService.js.map","/**\n * Collision Detection Service\n * Requirements: Translation Collision Handling - EARS 2.1, 2.2\n *\n * Detects existing translated documents for the same source document and target locale\n * to enable collision resolution handling.\n */\n/**\n * Error type for collision detection operations\n */\nexport class CollisionDetectionError extends Error {\n constructor(message, code, details) {\n super(message);\n this.code = code;\n this.details = details;\n this.name = 'CollisionDetectionError';\n }\n}\n/**\n * Service for detecting translation collisions\n *\n * A collision occurs when a translated document already exists for the same\n * source document and target locale. The service identifies collisions using:\n * 1. Parent reference matching: parentDocument._ref == sourceDocumentId AND locale == targetLocale\n * 2. Slug-locale matching: slug.current == slug AND locale == targetLocale\n */\nexport class CollisionDetectionService {\n constructor(client) {\n this.client = client;\n }\n /**\n * Detect if a collision exists for the given source document and target locale\n *\n * @param options - Options specifying the source document, target locale, and optional slug\n * @returns CollisionResult indicating whether a collision was found and details\n */\n async detectCollision(options) {\n const { sourceDocumentId, targetLocale, slug, documentType } = options;\n if (!sourceDocumentId || !targetLocale) {\n throw new CollisionDetectionError('sourceDocumentId and targetLocale are required', 'INVALID_OPTIONS');\n }\n // Strip drafts. prefix if present for consistent matching\n const cleanSourceId = sourceDocumentId.replace(/^drafts\\./, '');\n try {\n // First, check by parent reference\n const parentMatch = await this.findByParentReference(cleanSourceId, targetLocale, documentType);\n if (parentMatch) {\n console.log(`[CollisionDetection] Found collision by parent reference: ${parentMatch._id}`);\n return {\n detected: true,\n existingDocument: parentMatch,\n matchedBy: 'parent'\n };\n }\n // If no parent match and slug is provided, check by slug + locale\n if (slug) {\n const slugMatch = await this.findBySlugAndLocale(slug, targetLocale, documentType);\n if (slugMatch) {\n console.log(`[CollisionDetection] Found collision by slug-locale: ${slugMatch._id}`);\n return {\n detected: true,\n existingDocument: slugMatch,\n matchedBy: 'slug-locale'\n };\n }\n }\n // No collision found\n console.log(`[CollisionDetection] No collision detected for source ${cleanSourceId}, locale ${targetLocale}`);\n return {\n detected: false\n };\n }\n catch (error) {\n console.error('[CollisionDetection] Error during collision detection:', error);\n throw new CollisionDetectionError('Failed to detect collision', 'DETECTION_FAILED', error);\n }\n }\n /**\n * Find an existing document by parent reference and locale\n *\n * @param sourceDocumentId - The ID of the source/parent document\n * @param targetLocale - The target locale code\n * @param documentType - Optional document type to filter by\n */\n async findByParentReference(sourceDocumentId, targetLocale, documentType) {\n // Build query to find documents with matching parent reference and locale\n // Handle both drafts and published versions by checking both ID patterns\n // Also handle cases where locale is null but encoded in the document ID\n const typeFilter = documentType ? `&& _type == $documentType` : '';\n // First, try to find with explicit locale field\n const queryWithLocale = `*[\n (\n parentDocument._ref == $sourceId ||\n parentDocument._ref == $sourceIdWithDrafts\n ) &&\n (\n locale == $targetLocale ||\n locale.value == $targetLocale\n )\n ${typeFilter}\n ][0]`;\n // Fallback: Find by parent ref and locale pattern in document ID\n // Pattern: {sourceId}-{locale}-{timestamp} e.g., \"abc123-ja-JP-1234567890\"\n const queryWithIdPattern = `*[\n (\n parentDocument._ref == $sourceId ||\n parentDocument._ref == $sourceIdWithDrafts\n ) &&\n _id match $idPattern\n ${typeFilter}\n ][0]`;\n const params = {\n sourceId: sourceDocumentId,\n sourceIdWithDrafts: `drafts.${sourceDocumentId}`,\n targetLocale,\n idPattern: `*-${targetLocale}-*`\n };\n if (documentType) {\n params.documentType = documentType;\n }\n // Try with explicit locale field first\n let result = await this.client.fetch(queryWithLocale, params);\n // If not found, try with ID pattern matching\n if (!result) {\n result = await this.client.fetch(queryWithIdPattern, params);\n }\n return result || null;\n }\n /**\n * Find an existing document by slug and locale\n *\n * @param slug - The document slug to match\n * @param targetLocale - The target locale code\n * @param documentType - Optional document type to filter by\n */\n async findBySlugAndLocale(slug, targetLocale, documentType) {\n const typeFilter = documentType ? `&& _type == $documentType` : '';\n // Query for documents with matching slug and locale (explicit locale field)\n const queryWithLocale = `*[\n (\n slug == $slug ||\n slug.current == $slug\n ) &&\n (\n locale == $targetLocale ||\n locale.value == $targetLocale\n )\n ${typeFilter}\n ][0]`;\n // Fallback: Find by slug match and locale pattern in document ID\n // This handles documents where locale is null but encoded in the ID\n const queryWithIdPattern = `*[\n (\n slug == $slug ||\n slug.current == $slug\n ) &&\n _id match $idPattern\n ${typeFilter}\n ][0]`;\n const params = {\n slug,\n targetLocale,\n idPattern: `*-${targetLocale}-*`\n };\n if (documentType) {\n params.documentType = documentType;\n }\n // Try with explicit locale field first\n let result = await this.client.fetch(queryWithLocale, params);\n // If not found, try with ID pattern matching\n if (!result) {\n result = await this.client.fetch(queryWithIdPattern, params);\n }\n return result || null;\n }\n /**\n * Check if multiple collisions exist for bulk translation operations\n *\n * @param sourceDocumentId - The source document being translated\n * @param targetLocales - Array of target locale codes\n * @param slug - Optional slug for slug-locale matching\n * @param documentType - Optional document type to filter by\n * @returns Map of locale code to collision result\n */\n async detectBulkCollisions(sourceDocumentId, targetLocales, slug, documentType) {\n const results = new Map();\n // Process each locale\n for (const targetLocale of targetLocales) {\n try {\n const result = await this.detectCollision({\n sourceDocumentId,\n targetLocale,\n slug,\n documentType\n });\n results.set(targetLocale, result);\n }\n catch (error) {\n console.error(`[CollisionDetection] Error checking locale ${targetLocale}:`, error);\n // Set as no collision detected but log the error\n results.set(targetLocale, { detected: false });\n }\n }\n return results;\n }\n}\n//# sourceMappingURL=collisionDetectionService.js.map","import { CollisionDetectionService } from './collisionDetectionService';\nexport class DocumentCreationService {\n constructor(client, defaultCreationMode) {\n this.defaultCreationMode = 'draft';\n this.collisionDetectionService = null;\n this.defaultCollisionResolutionMode = 'replace';\n this.defaultExistingDocumentHandling = 'draft';\n this.client = client;\n if (defaultCreationMode) {\n this.defaultCreationMode = defaultCreationMode;\n }\n // Initialize collision detection service\n this.collisionDetectionService = new CollisionDetectionService(client);\n }\n /**\n * Set the default document creation mode\n * @param mode - The creation mode to use by default ('draft' or 'published')\n */\n setDefaultCreationMode(mode) {\n this.defaultCreationMode = mode;\n }\n /**\n * Set the default collision resolution mode\n * @param mode - How to handle collisions ('replace' or 'create')\n */\n setDefaultCollisionResolutionMode(mode) {\n this.defaultCollisionResolutionMode = mode;\n }\n /**\n * Set the default existing document handling mode\n * @param handling - How to handle existing documents when creating new ('draft' or 'delete')\n */\n setDefaultExistingDocumentHandling(handling) {\n this.defaultExistingDocumentHandling = handling;\n }\n /**\n * Configure collision resolution defaults\n * @param mode - Collision resolution mode\n * @param handling - Existing document handling (only applicable when mode is 'create')\n */\n setCollisionResolutionConfig(mode, handling) {\n this.defaultCollisionResolutionMode = mode;\n if (handling) {\n this.defaultExistingDocumentHandling = handling;\n }\n }\n /**\n * Replace an existing document with new translated content\n * Requirements: EARS 4 - Resolution Behavior - Replace\n *\n * @param existingDocument - The document to replace\n * @param newDocument - The new translated document content\n * @param creationMode - Whether to create as draft or published\n */\n async replaceExistingDocument(existingDocument, newDocument, creationMode) {\n try {\n // Use the existing document's ID for the replacement\n const existingId = existingDocument._id;\n const isExistingDraft = existingId.startsWith('drafts.');\n // Prepare the document with the existing ID\n const documentToSave = {\n ...newDocument,\n _id: existingId,\n // Preserve system fields from existing document\n _createdAt: existingDocument._createdAt\n };\n // Remove fields that Sanity will manage\n delete documentToSave._rev;\n delete documentToSave._updatedAt;\n console.log(`[ReplaceDocument] Replacing document ${existingId}`);\n // Use createOrReplace to overwrite the existing document\n const replacedDocument = await this.client.createOrReplace(documentToSave);\n console.log(`[ReplaceDocument] Successfully replaced document ${replacedDocument._id}`);\n // Handle draft/published state if different from existing\n if (creationMode === 'draft' && !isExistingDraft) {\n // Existing is published but we want draft - create draft version\n const draftId = `drafts.${existingId}`;\n const draftDoc = await this.client.createOrReplace({\n ...documentToSave,\n _id: draftId\n });\n return {\n success: true,\n documentId: draftDoc._id,\n document: draftDoc\n };\n }\n else if (creationMode === 'published' && isExistingDraft) {\n // Existing is draft but we want published - create published version\n const publishedId = existingId.replace(/^drafts\\./, '');\n const publishedDoc = await this.client.createOrReplace({\n ...documentToSave,\n _id: publishedId\n });\n return {\n success: true,\n documentId: publishedDoc._id,\n document: publishedDoc\n };\n }\n return {\n success: true,\n documentId: replacedDocument._id,\n document: replacedDocument\n };\n }\n catch (error) {\n console.error('[ReplaceDocument] Failed to replace document:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error during document replacement'\n };\n }\n }\n /**\n * Handle an existing document when creating a new translation (for 'create' mode)\n * Requirements: EARS 5 - Resolution Behavior - Create\n *\n * @param existingDocument - The existing document to handle\n * @param handling - How to handle the existing document ('draft' or 'delete')\n */\n async handleExistingDocument(existingDocument, handling) {\n try {\n const existingId = existingDocument._id;\n if (handling === 'delete') {\n // Delete the existing document\n console.log(`[HandleExistingDocument] Deleting document ${existingId}`);\n await this.client.delete(existingId);\n // Also delete draft version if exists\n if (!existingId.startsWith('drafts.')) {\n try {\n await this.client.delete(`drafts.${existingId}`);\n }\n catch {\n // Draft might not exist, ignore\n }\n }\n console.log(`[HandleExistingDocument] Successfully deleted document ${existingId}`);\n return { success: true };\n }\n else if (handling === 'draft') {\n // Set the existing document to draft state\n console.log(`[HandleExistingDocument] Setting document ${existingId} to draft state`);\n if (existingId.startsWith('drafts.')) {\n // Already a draft, nothing to do\n console.log(`[HandleExistingDocument] Document ${existingId} is already a draft`);\n return { success: true };\n }\n // For published documents, we need to create a draft and optionally unpublish\n // Create draft version\n const draftId = `drafts.${existingId}`;\n // Create the draft document\n await this.client.createOrReplace({\n ...existingDocument,\n _id: draftId,\n _rev: undefined, // Remove revision\n _createdAt: undefined,\n _updatedAt: undefined\n });\n // Delete the published version to effectively \"unpublish\"\n await this.client.delete(existingId);\n console.log(`[HandleExistingDocument] Successfully set document to draft: ${draftId}`);\n return { success: true };\n }\n return { success: true };\n }\n catch (error) {\n console.error('[HandleExistingDocument] Failed to handle existing document:', error);\n return {\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error during existing document handling'\n };\n }\n }\n /**\n * Create a new Sanity document from translation response\n * Requirements: 1.1, 1.2, 2.1, 3.2, 3.4\n */\n async createDocumentFromTranslation(originalDocument, translationResponse, options = {}) {\n try {\n // Enhanced input validation\n const inputValidation = this.validateInputsForDocumentCreation(originalDocument, translationResponse, options);\n if (!inputValidation.isValid) {\n return {\n success: false,\n error: `Input validation failed: ${inputValidation.errors.join(', ')}`\n };\n }\n // Get translated content (support both new array format and legacy formats)\n const translatedContent = translationResponse.translatedDocuments?.[0] ||\n translationResponse.translatedContent;\n // DEBUG: Log titleFoundAtTopLevel from options (tracked in-memory, not from translation response)\n console.log('[DocumentCreation] createDocumentFromTranslation:', {\n titleFoundAtTopLevelFromOptions: options.titleFoundAtTopLevel,\n translatedContentKeys: translatedContent ? Object.keys(translatedContent) : []\n });\n if (!translationResponse.success || !translatedContent) {\n return {\n success: false,\n error: 'Translation response does not contain valid translated content'\n };\n }\n // Validate translation response content\n const responseValidation = this.validateTranslationResponseForCreation(translationResponse);\n if (!responseValidation.isValid) {\n return {\n success: false,\n error: `Translation response validation failed: ${responseValidation.errors.join(', ')}`\n };\n }\n // Merge translated content back into original document structure\n const newDocument = await this.mergeTranslatedContent(originalDocument, translatedContent, options);\n // Validate the new document structure\n const validationResult = this.validateDocumentStructure(newDocument);\n if (!validationResult.isValid) {\n return {\n success: false,\n error: `Document validation failed: ${validationResult.errors.join(', ')}`\n };\n }\n // Additional business logic validation\n const businessValidation = this.validateBusinessRules(newDocument, originalDocument);\n if (!businessValidation.isValid) {\n return {\n success: false,\n error: `Business rule validation failed: ${businessValidation.errors.join(', ')}`\n };\n }\n // Handle slug fallback if needed\n let slugFallbackInfo;\n if (businessValidation.slugNeedsFallback) {\n const targetLocale = options.targetLanguage || 'translated';\n const originalSlug = typeof originalDocument.slug === 'object'\n ? originalDocument.slug.current\n : originalDocument.slug;\n const fallbackSlug = `${originalSlug}_${targetLocale}`;\n // Apply the fallback slug to the document\n if (typeof newDocument.slug === 'object' && newDocument.slug !== null && '_type' in newDocument.slug) {\n newDocument.slug = {\n _type: 'slug',\n current: fallbackSlug\n };\n }\n else {\n newDocument.slug = fallbackSlug;\n }\n slugFallbackInfo = {\n documentId: newDocument._id,\n originalSlug,\n fallbackSlug,\n locale: targetLocale,\n reason: 'Translation did not produce a different slug - locale suffix applied'\n };\n console.log(`[Slug Fallback Applied] Document ${newDocument._id}: \"${originalSlug}\" → \"${fallbackSlug}\"`);\n }\n // Determine effective creation mode (option override or default)\n const effectiveCreationMode = options.creationMode || this.defaultCreationMode;\n // Determine effective collision resolution settings\n const effectiveCollisionMode = options.collisionResolutionMode || this.defaultCollisionResolutionMode;\n const effectiveExistingDocHandling = options.existingDocumentHandling || this.defaultExistingDocumentHandling;\n // Detect collision if collision detection service is available\n let collisionResult = null;\n let collisionInfo;\n if (this.collisionDetectionService && options.targetLanguage && options.parentDocumentId) {\n const translatedSlug = typeof newDocument.slug === 'object' && newDocument.slug !== null && 'current' in newDocument.slug\n ? newDocument.slug.current\n : typeof newDocument.slug === 'string' ? newDocument.slug : undefined;\n collisionResult = await this.collisionDetectionService.detectCollision({\n sourceDocumentId: options.parentDocumentId,\n targetLocale: options.targetLanguage,\n slug: translatedSlug,\n documentType: originalDocument._type\n });\n if (collisionResult.detected) {\n console.log(`[CollisionHandling] Collision detected for source ${options.parentDocumentId}, locale ${options.targetLanguage}`);\n console.log(`[CollisionHandling] Resolution mode: ${effectiveCollisionMode}, Existing doc handling: ${effectiveExistingDocHandling}`);\n collisionInfo = {\n collisionDetected: true,\n matchedBy: collisionResult.matchedBy,\n existingDocumentId: collisionResult.existingDocument?._id\n };\n // Handle collision based on resolution mode\n if (effectiveCollisionMode === 'replace' && collisionResult.existingDocument) {\n // Replace mode: Overwrite the existing document\n const replaceResult = await this.replaceExistingDocument(collisionResult.existingDocument, newDocument, effectiveCreationMode);\n if (replaceResult.success) {\n collisionInfo.resolutionAction = 'replaced';\n collisionInfo.existingDocumentAction = 'none';\n return {\n success: true,\n documentId: replaceResult.documentId,\n document: replaceResult.document,\n slugFallback: slugFallbackInfo,\n collisionInfo\n };\n }\n else {\n return {\n success: false,\n error: `Failed to replace existing document: ${replaceResult.error}`,\n collisionInfo\n };\n }\n }\n else if (effectiveCollisionMode === 'create' && collisionResult.existingDocument) {\n // Create mode: Handle existing document, then create new\n const handleResult = await this.handleExistingDocument(collisionResult.existingDocument, effectiveExistingDocHandling);\n collisionInfo.resolutionAction = 'created_new';\n collisionInfo.existingDocumentAction = effectiveExistingDocHandling === 'draft' ? 'set_to_draft' : 'deleted';\n if (!handleResult.success) {\n console.warn(`[CollisionHandling] Failed to handle existing document: ${handleResult.error}`);\n // Continue with document creation even if existing doc handling fails\n }\n }\n }\n else {\n collisionInfo = {\n collisionDetected: false,\n resolutionAction: 'none'\n };\n }\n }\n // Actually create the document in Sanity\n try {\n let createdDocument;\n if (effectiveCreationMode === 'draft') {\n // Create as draft document by prefixing ID with 'drafts.'\n const draftId = newDocument._id.startsWith('drafts.')\n ? newDocument._id\n : `drafts.${newDocument._id}`;\n console.log('Creating draft document in Sanity:', draftId);\n createdDocument = await this.client.create({\n ...newDocument,\n _id: draftId\n });\n console.log('Draft document created successfully:', createdDocument._id);\n }\n else {\n // Create as published document (no prefix)\n // Strip 'drafts.' prefix if present to ensure it's a published document\n const publishedId = newDocument._id.startsWith('drafts.')\n ? newDocument._id.replace(/^drafts\\./, '')\n : newDocument._id;\n console.log('Creating published document in Sanity:', publishedId);\n createdDocument = await this.client.create({\n ...newDocument,\n _id: publishedId\n });\n console.log('Published document created successfully:', createdDocument._id);\n }\n return {\n success: true,\n documentId: createdDocument._id,\n document: createdDocument,\n slugFallback: slugFallbackInfo,\n collisionInfo\n };\n }\n catch (sanityError) {\n console.error('Failed to create document in Sanity:', sanityError);\n return {\n success: false,\n error: `Failed to save document to Sanity: ${sanityError instanceof Error ? sanityError.message : 'Unknown Sanity error'}`\n };\n }\n }\n catch (error) {\n // Enhanced error handling with more context\n const errorMessage = this.formatErrorMessage(error, originalDocument._id);\n return {\n success: false,\n error: errorMessage\n };\n }\n }\n /**\n * Validate inputs for document creation\n * Requirements: 4.3, 4.4\n */\n validateInputsForDocumentCreation(originalDocument, translationResponse, options) {\n const errors = [];\n // Validate original document\n if (!originalDocument) {\n errors.push('Original document is required');\n return { isValid: false, errors };\n }\n if (!originalDocument._id) {\n errors.push('Original document must have an _id');\n }\n if (!originalDocument._type) {\n errors.push('Original document must have a _type');\n }\n // Validate translation response\n if (!translationResponse) {\n errors.push('Translation response is required');\n return { isValid: false, errors };\n }\n // Validate options\n if (options.targetLanguage && typeof options.targetLanguage !== 'string') {\n errors.push('Target language must be a string');\n }\n if (options.sourceLanguage && typeof options.sourceLanguage !== 'string') {\n errors.push('Source language must be a string');\n }\n if (options.createAsVariant !== undefined && typeof options.createAsVariant !== 'boolean') {\n errors.push('createAsVariant must be a boolean');\n }\n if (options.parentDocumentId && typeof options.parentDocumentId !== 'string') {\n errors.push('parentDocumentId must be a string');\n }\n return {\n isValid: errors.length === 0,\n errors\n };\n }\n /**\n * Validate business rules for document creation\n * Requirements: 4.3, 4.4\n */\n validateBusinessRules(newDocument, originalDocument) {\n const errors = [];\n let slugNeedsFallback = false;\n // Ensure new document has different ID from original\n if (newDocument._id === originalDocument._id) {\n errors.push('New document ID must be different from original document ID');\n }\n // Ensure new document has same type as original\n if (newDocument._type !== originalDocument._type) {\n errors.push(`New document type (${newDocument._type}) must match original document type (${originalDocument._type})`);\n }\n // Validate that essential content exists\n const hasContent = this.documentHasContent(newDocument);\n if (!hasContent) {\n errors.push('New document must contain some translatable content');\n }\n // Check slug uniqueness - if same as original, mark for fallback instead of error\n if (newDocument.slug && originalDocument.slug) {\n const newSlug = typeof newDocument.slug === 'object' ? newDocument.slug.current : newDocument.slug;\n const originalSlug = typeof originalDocument.slug === 'object' ? originalDocument.slug.current : originalDocument.slug;\n if (newSlug === originalSlug) {\n // Log warning instead of failing\n console.warn(`[Slug Fallback] Document ${newDocument._id}: Slug \"${newSlug}\" is same as original. Will apply locale suffix.`);\n slugNeedsFallback = true;\n }\n }\n return {\n isValid: errors.length === 0,\n errors,\n slugNeedsFallback\n };\n }\n /**\n * Check if document has meaningful content\n * Searches both top-level and nested fields for title/body content\n */\n documentHasContent(document) {\n const titleFields = ['title', 'name', 'heading', 'label'];\n const contentFields = ['body', 'content'];\n // Check for title at top level\n for (const field of titleFields) {\n if (document[field] && typeof document[field] === 'string' && document[field].trim().length > 0) {\n return true;\n }\n }\n // Check for body content at top level\n for (const field of contentFields) {\n if (document[field]) {\n if (typeof document[field] === 'string' && document[field].trim().length > 0) {\n return true;\n }\n if (Array.isArray(document[field]) && document[field].length > 0) {\n return true;\n }\n }\n }\n // Search nested fields for title or body content\n if (this.hasContentInNestedFields(document, titleFields, contentFields)) {\n return true;\n }\n return false;\n }\n /**\n * Recursively search nested objects for title or body content\n */\n hasContentInNestedFields(obj, titleFields, contentFields) {\n for (const [key, value] of Object.entries(obj)) {\n // Skip system/internal fields\n if (key.startsWith('_')) {\n continue;\n }\n if (value === null || value === undefined) {\n continue;\n }\n // Check nested objects\n if (typeof value === 'object' && !Array.isArray(value)) {\n // Check if this nested object has a title field\n for (const titleField of titleFields) {\n if (value[titleField] && typeof value[titleField] === 'string' && value[titleField].trim().length > 0) {\n return true;\n }\n }\n // Check if this nested object has a body field\n for (const contentField of contentFields) {\n if (value[contentField]) {\n if (typeof value[contentField] === 'string' && value[contentField].trim().length > 0) {\n return true;\n }\n if (Array.isArray(value[contentField]) && value[contentField].length > 0) {\n return true;\n }\n }\n }\n // Recursively search deeper\n if (this.hasContentInNestedFields(value, titleFields, contentFields)) {\n return true;\n }\n }\n // Also search within arrays\n if (Array.isArray(value)) {\n for (const item of value) {\n if (item && typeof item === 'object') {\n // Check if this array item has title/body fields\n for (const titleField of titleFields) {\n if (item[titleField] && typeof item[titleField] === 'string' && item[titleField].trim().length > 0) {\n return true;\n }\n }\n for (const contentField of contentFields) {\n if (item[contentField]) {\n if (typeof item[contentField] === 'string' && item[contentField].trim().length > 0) {\n return true;\n }\n if (Array.isArray(item[contentField]) && item[contentField].length > 0) {\n return true;\n }\n }\n }\n // Recursively search deeper\n if (this.hasContentInNestedFields(item, titleFields, contentFields)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n /**\n * Format error messages with additional context\n * Requirements: 4.3, 4.4\n */\n formatErrorMessage(error, documentId) {\n const baseMessage = error instanceof Error ? error.message : 'Unknown error occurred during document creation';\n const contextInfo = documentId ? ` (Document ID: ${documentId})` : '';\n // Add specific error handling for common issues\n if (error instanceof Error) {\n if (error.message.includes('validation')) {\n return `Document validation error${contextInfo}: ${error.message}`;\n }\n if (error.message.includes('network') || error.message.includes('fetch')) {\n return `Network error during document creation${contextInfo}: ${error.message}`;\n }\n if (error.message.includes('permission') || error.message.includes('unauthorized')) {\n return `Permission error during document creation${contextInfo}: ${error.message}`;\n }\n }\n return `Document creation error${contextInfo}: ${baseMessage}`;\n }\n /**\n * Create multiple documents from bulk translation responses\n * Requirements: 2.1, 3.2, 3.4\n */\n async createBulkDocumentsFromTranslations(originalDocuments, translationResponses, options = {}) {\n const result = {\n totalDocuments: originalDocuments.length,\n successfulCreations: 0,\n failedCreations: 0,\n results: [],\n errors: [],\n rollbackInfo: {\n canRollback: true,\n createdDocumentIds: [],\n rollbackInstructions: []\n },\n slugFallbacks: []\n };\n // Pre-validate all translation responses before creating any documents\n const validationErrors = this.validateBulkTranslationResponses(originalDocuments, translationResponses);\n if (validationErrors.length > 0) {\n result.errors.push(...validationErrors);\n result.failedCreations = originalDocuments.length;\n result.rollbackInfo.canRollback = false;\n result.rollbackInfo.rollbackInstructions.push('No documents were created due to validation failures');\n // Add individual failure results\n for (let i = 0; i < originalDocuments.length; i++) {\n result.results.push({\n success: false,\n error: 'Bulk validation failed - no documents created'\n });\n }\n return result;\n }\n // Track successful creations for potential rollback\n const createdDocuments = [];\n for (let i = 0; i < originalDocuments.length; i++) {\n const originalDocument = originalDocuments[i];\n const translationResponse = translationResponses[i];\n if (!translationResponse) {\n const error = `No translation response found for document ${originalDocument._id}`;\n result.results.push({\n success: false,\n error\n });\n result.errors.push(error);\n result.failedCreations++;\n continue;\n }\n try {\n // Additional validation before creation\n const preCreationValidation = this.validateTranslationResponseForCreation(translationResponse);\n if (!preCreationValidation.isValid) {\n const error = `Pre-creation validation failed for ${originalDocument._id}: ${preCreationValidation.errors.join(', ')}`;\n result.results.push({\n success: false,\n error\n });\n result.errors.push(error);\n result.failedCreations++;\n continue;\n }\n // Get all translated documents (support both new array format and legacy single document format)\n const translatedDocuments = translationResponse.translatedDocuments ||\n (translationResponse.translatedContent ? [translationResponse.translatedContent] : []);\n if (translatedDocuments.length === 0) {\n const error = `No translated documents found in response for ${originalDocument._id}`;\n result.results.push({\n success: false,\n error\n });\n result.errors.push(error);\n result.failedCreations++;\n continue;\n }\n // Create a document for each translated document in the response\n for (let j = 0; j < translatedDocuments.length; j++) {\n const translatedContent = translatedDocuments[j];\n // Extract TARGET locale from the translated content\n // Priority: \n // 1. translatedContent.locale (document-level locale set by translation service - this IS the target)\n // 2. options.targetLanguage (from request metadata)\n // 3. fallback to 'translated'\n // NOTE: Do NOT use translatedContent.fields?.locale as that contains the \n // locale FIELD VALUE from the document, not the translation target\n const targetLocale = (translatedContent.locale ||\n options.targetLanguage ||\n 'translated');\n console.log(`Creating document for ${originalDocument._id} with target locale: ${targetLocale}`);\n // Create a single-document translation response for this document\n const singleDocumentResponse = {\n ...translationResponse,\n translatedDocuments: [translatedContent],\n translatedContent: translatedContent\n };\n const creationResult = await this.createDocumentFromTranslation(originalDocument, singleDocumentResponse, {\n ...options,\n targetLanguage: targetLocale\n });\n result.results.push(creationResult);\n if (creationResult.success && creationResult.documentId) {\n result.successfulCreations++;\n createdDocuments.push({\n documentId: creationResult.documentId,\n originalId: originalDocument._id\n });\n result.rollbackInfo.createdDocumentIds.push(creationResult.documentId);\n // Collect slug fallback info if applicable\n if (creationResult.slugFallback) {\n result.slugFallbacks.push(creationResult.slugFallback);\n }\n }\n else {\n result.failedCreations++;\n if (creationResult.error) {\n result.errors.push(creationResult.error);\n }\n }\n }\n }\n catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';\n result.results.push({\n success: false,\n error: errorMessage\n });\n result.errors.push(errorMessage);\n result.failedCreations++;\n }\n }\n // Generate rollback instructions\n if (result.successfulCreations > 0) {\n result.rollbackInfo.rollbackInstructions = [\n `${result.successfulCreations} documents were successfully created.`,\n 'To rollback these changes, you would need to delete the following document IDs:',\n ...result.rollbackInfo.createdDocumentIds.map(id => `- ${id}`),\n 'Note: This plugin does not automatically delete documents for safety reasons.',\n 'Manual deletion through Sanity Studio or API calls would be required.'\n ];\n }\n else {\n result.rollbackInfo.rollbackInstructions = ['No documents were created, no rollback needed.'];\n }\n // Log slug fallback summary if any occurred\n if (result.slugFallbacks.length > 0) {\n console.log(`[Slug Fallback Summary] ${result.slugFallbacks.length} document(s) had slug fallback applied:`);\n result.slugFallbacks.forEach(fallback => {\n console.log(` - ${fallback.documentId}: \"${fallback.originalSlug}\" → \"${fallback.fallbackSlug}\" (locale: ${fallback.locale})`);\n });\n }\n return result;\n }\n /**\n * Validate bulk translation responses before document creation\n * Requirements: 4.3, 4.4\n */\n validateBulkTranslationResponses(originalDocuments, translationResponses) {\n const errors = [];\n // Check array lengths match\n if (originalDocuments.length !== translationResponses.length) {\n errors.push(`Mismatch between original documents (${originalDocuments.length}) and translation responses (${translationResponses.length})`);\n return errors; // Critical error, return immediately\n }\n // Validate each pair\n for (let i = 0; i < originalDocuments.length; i++) {\n const originalDoc = originalDocuments[i];\n const response = translationResponses[i];\n if (!originalDoc) {\n errors.push(`Original document at index ${i} is null or undefined`);\n continue;\n }\n if (!originalDoc._id) {\n errors.push(`Original document at index ${i} missing _id`);\n continue;\n }\n if (!originalDoc._type) {\n errors.push(`Original document at index ${i} missing _type`);\n continue;\n }\n if (!response) {\n errors.push(`Translation response at index ${i} is null or undefined`);\n continue;\n }\n if (!response.success) {\n // This is not necessarily an error for bulk validation, just skip this document\n continue;\n }\n // Check for translated content (support both new array format and legacy formats)\n const translatedDocuments = response.translatedDocuments ||\n (response.translatedContent ? [response.translatedContent] : []);\n if (translatedDocuments.length === 0) {\n errors.push(`Translation response at index ${i} missing translatedDocuments/translatedContent despite success=true`);\n continue;\n }\n }\n return errors;\n }\n /**\n * Validate translation response before document creation\n * Requirements: 4.3, 4.4\n */\n validateTranslationResponseForCreation(response) {\n const errors = [];\n if (!response.success) {\n errors.push('Translation response indicates failure');\n return { isValid: false, errors };\n }\n // Get translated content (support both new array format and legacy formats)\n const translatedDocuments = response.translatedDocuments ||\n (response.translatedContent ? [response.translatedContent] : []);\n if (translatedDocuments.length === 0) {\n errors.push('Translation response missing translatedDocuments/translatedContent');\n return { isValid: false, errors };\n }\n // Validate each translated document structure\n for (let i = 0; i < translatedDocuments.length; i++) {\n const content = translatedDocuments[i];\n if (typeof content !== 'object' || content === null) {\n errors.push(`Translated document at index ${i} must be an object`);\n continue;\n }\n // Check for required fields\n if (!content.body && !content.title && !content.fields) {\n errors.push(`Translated document at index ${i} must contain at least one of: body, title, or fields`);\n }\n // Validate body content if present\n if (content.body !== undefined) {\n if (typeof content.body !== 'string') {\n errors.push(`Translated document at index ${i} body must be a string`);\n }\n else if (content.body.trim().length === 0) {\n errors.push(`Translated document at index ${i} body cannot be empty`);\n }\n }\n // Validate title if present\n if (content.title !== undefined) {\n if (typeof content.title !== 'string') {\n errors.push(`Translated document at index ${i} title must be a string`);\n }\n else if (content.title.trim().length === 0) {\n errors.push(`Translated document at index ${i} title cannot be empty`);\n }\n }\n // Validate slug if present\n if (content.slug !== undefined) {\n if (typeof content.slug !== 'string') {\n errors.push(`Translated document at index ${i} slug must be a string`);\n }\n else if (content.slug.trim().length === 0) {\n errors.push(`Translated document at index ${i} slug cannot be empty`);\n }\n else if (!/^[a-z0-9-_]+$/.test(content.slug)) {\n errors.push(`Translated document at index ${i} slug must contain only lowercase letters, numbers, hyphens, and underscores`);\n }\n }\n // Validate fields if present\n if (content.fields !== undefined) {\n if (typeof content.fields !== 'object' || content.fields === null || Array.isArray(content.fields)) {\n errors.push(`Translated document at index ${i} fields must be an object`);\n }\n }\n }\n return {\n isValid: errors.length === 0,\n errors\n };\n }\n /**\n * Create rollback plan for failed bulk operations\n * Requirements: 4.3, 4.4\n */\n createRollbackPlan(createdDocumentIds) {\n if (createdDocumentIds.length === 0) {\n return {\n canRollback: true,\n createdDocumentIds: [],\n rollbackInstructions: ['No documents were created, no rollback needed.']\n };\n }\n return {\n canRollback: true,\n createdDocumentIds: [...createdDocumentIds],\n rollbackInstructions: [\n `Rollback plan for ${createdDocumentIds.length} created documents:`,\n '',\n '1. Manual deletion required (for safety):',\n ...createdDocumentIds.map(id => ` - Delete document: ${id}`),\n '',\n '2. Alternative: Use Sanity CLI or API:',\n ' sanity documents delete <document-id>',\n '',\n '3. Or via Sanity Client API:',\n ' client.delete(documentId)',\n '',\n 'WARNING: This plugin does not provide automatic rollback to prevent',\n 'accidental data loss. Please review each document before deletion.'\n ]\n };\n }\n /**\n * Parse a field path that may contain array key selectors\n * e.g., \"article.footnotes[_key == \\\"c82437b14d71\\\"].footnote\"\n *\n * @param fieldPath - The field path (may be from the field key or from the path property)\n * @returns Array of path segments with type information\n */\n parseFieldPath(fieldPath) {\n const segments = [];\n // Strip GROQ query prefix if present: *[_type == \"...\" && _id == $documentId][0].\n const groqPrefixMatch = fieldPath.match(/^\\*\\[.*?\\]\\[0\\]\\./);\n const cleanPath = groqPrefixMatch ? fieldPath.substring(groqPrefixMatch[0].length) : fieldPath;\n // Split by dots, but handle array key selectors like [_key == \"value\"]\n // Regex to match: propertyName or propertyName[_key == \"value\"]\n const segmentRegex = /([^.[]+)(?:\\[_key\\s*==\\s*\"([^\"]+)\"\\])?/g;\n let match;\n while ((match = segmentRegex.exec(cleanPath)) !== null) {\n const [, propertyName, keyValue] = match;\n if (keyValue) {\n // This is an array property with a key selector\n segments.push({ type: 'arrayKey', name: propertyName, key: keyValue });\n }\n else {\n // Regular property\n segments.push({ type: 'property', name: propertyName });\n }\n // Skip the dot after the match if present\n if (cleanPath[segmentRegex.lastIndex] === '.') {\n segmentRegex.lastIndex++;\n }\n }\n return segments;\n }\n /**\n * Unflatten fields with complex paths back into nested objects\n * Handles both simple dotted paths and GROQ-style array key paths:\n * - \"metadata.version\" → { metadata: { version: ... } }\n * - \"article.footnotes[_key == \\\"abc\\\"].footnote\" → { article: { footnotes: [{ _key: \"abc\", footnote: ... }] } }\n *\n * @param fields - Flattened fields with path keys\n * @param originalDocument - Original document for preserving array structure\n * @returns Unflattened nested object structure\n */\n unflattenFields(fields, originalDocument) {\n const result = {};\n for (const [fieldKey, fieldValue] of Object.entries(fields)) {\n // Use the path property if available, otherwise use the field key\n const fieldPath = (fieldValue && typeof fieldValue === 'object' && 'path' in fieldValue)\n ? fieldValue.path\n : fieldKey;\n // Parse the path into segments\n const segments = this.parseFieldPath(fieldPath);\n if (segments.length === 0) {\n continue;\n }\n // Extract the actual value from TranslatableField if needed\n let actualValue = fieldValue;\n let fieldType;\n if (fieldValue && typeof fieldValue === 'object' && 'value' in fieldValue) {\n actualValue = fieldValue.value;\n fieldType = fieldValue.type;\n // Parse JSON strings back to objects if needed\n if (typeof actualValue === 'string') {\n // Check if it's a JSON string (arrays or objects)\n if ((actualValue.startsWith('[') && actualValue.endsWith(']')) ||\n (actualValue.startsWith('{') && actualValue.endsWith('}'))) {\n try {\n actualValue = JSON.parse(actualValue);\n }\n catch {\n // Keep as string if parsing fails\n }\n }\n }\n // Convert HTML content back to portable text for 'block' type fields\n if (fieldType === 'block' && typeof actualValue === 'string' && this.isHtmlContent(actualValue)) {\n actualValue = this.convertHtmlToPortableText(actualValue);\n }\n }\n // Navigate/create the nested structure\n let current = result;\n let originalCurrent = originalDocument;\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i];\n const isLastSegment = i === segments.length - 1;\n if (segment.type === 'arrayKey') {\n // This is an array property with a key selector\n if (!(segment.name in current)) {\n // Initialize array, copying structure from original if available\n if (originalCurrent && Array.isArray(originalCurrent[segment.name])) {\n // Deep clone the original array to preserve all items and their structure\n current[segment.name] = JSON.parse(JSON.stringify(originalCurrent[segment.name]));\n }\n else {\n current[segment.name] = [];\n }\n }\n // Find or create the array item with the matching key\n const array = current[segment.name];\n let arrayItem = array.find((item) => item._key === segment.key);\n if (!arrayItem) {\n // Create a new array item with the key\n // Try to copy structure from original if available\n let originalItem = null;\n if (originalCurrent && Array.isArray(originalCurrent[segment.name])) {\n originalItem = originalCurrent[segment.name].find((item) => item._key === segment.key);\n }\n if (originalItem) {\n arrayItem = JSON.parse(JSON.stringify(originalItem));\n }\n else {\n arrayItem = { _key: segment.key };\n }\n array.push(arrayItem);\n }\n if (isLastSegment) {\n // This shouldn't happen - array key selectors should have a property after them\n // But handle it just in case\n Object.assign(arrayItem, actualValue);\n }\n else {\n current = arrayItem;\n originalCurrent = originalCurrent?.[segment.name]?.find((item) => item._key === segment.key);\n }\n }\n else {\n // Regular property\n if (isLastSegment) {\n // Set the leaf value\n current[segment.name] = actualValue;\n }\n else {\n // Navigate/create intermediate object\n if (!(segment.name in current)) {\n // Try to copy structure from original if available\n if (originalCurrent && typeof originalCurrent[segment.name] === 'object' && originalCurrent[segment.name] !== null) {\n current[segment.name] = Array.isArray(originalCurrent[segment.name])\n ? JSON.parse(JSON.stringify(originalCurrent[segment.name]))\n : { ...originalCurrent[segment.name] };\n }\n else {\n current[segment.name] = {};\n }\n }\n current = current[segment.name];\n originalCurrent = originalCurrent?.[segment.name];\n }\n }\n }\n }\n return result;\n }\n /**\n * Get the original nested value from the original document using a dotted path\n *\n * @param document - The original document\n * @param fieldPath - The dotted path to the field\n * @returns The original value at the path, or undefined\n */\n getOriginalValueByPath(document, fieldPath) {\n const pathParts = fieldPath.split('.');\n let current = document;\n for (const part of pathParts) {\n if (current === null || current === undefined || typeof current !== 'object') {\n return undefined;\n }\n current = current[part];\n }\n return current;\n }\n /**\n * Merge translated content back into original document structure\n * Requirements: 1.2, 3.2, 3.4\n */\n async mergeTranslatedContent(originalDocument, translatedContent, options) {\n // Extract the TARGET locale early for document ID generation\n // Priority: \n // 1. options.targetLanguage (explicitly passed from caller)\n // 2. translatedContent.locale (document-level locale set by translation service - this IS the target)\n // NOTE: Do NOT use translatedContent.fields?.locale as that contains the locale\n // FIELD VALUE from the document, not the translation target\n const targetLang = options.targetLanguage || translatedContent.locale;\n // Create a new document based on the original\n const newDocument = {\n ...originalDocument,\n _id: this.generateNewDocumentId(originalDocument._id, targetLang),\n // Remove system fields - they will be set by Sanity\n _rev: undefined,\n _createdAt: undefined,\n _updatedAt: undefined,\n };\n // Update title if provided AND the original had a top-level title\n // (Don't create a new top-level title field if the original only had nested title fields)\n // Use the value from options (tracked in-memory by the plugin), not from translatedContent\n const shouldWriteTopLevelTitle = options.titleFoundAtTopLevel !== false;\n // DEBUG: Title handling trace\n console.log('[DocumentCreation] Title handling:', {\n originalDocumentTitle: originalDocument.title,\n originalDocumentHasTitle: 'title' in originalDocument,\n translatedContentTitle: translatedContent.title,\n titleFoundAtTopLevelFromOptions: options.titleFoundAtTopLevel,\n shouldWriteTopLevelTitle,\n newDocumentTitleBefore: newDocument.title\n });\n if (translatedContent.title && translatedContent.title.trim() && shouldWriteTopLevelTitle) {\n newDocument.title = translatedContent.title;\n console.log('[DocumentCreation] Writing title to top level:', translatedContent.title);\n }\n else {\n // If we shouldn't write a top-level title, make sure we don't have one from the spread\n if (!shouldWriteTopLevelTitle && 'title' in newDocument) {\n console.log('[DocumentCreation] Removing inherited top-level title field');\n delete newDocument.title;\n }\n else {\n console.log('[DocumentCreation] NOT writing title. Reason:', {\n hasTitle: !!translatedContent.title,\n titleNotEmpty: translatedContent.title?.trim() ? true : false,\n shouldWriteTopLevelTitle\n });\n }\n }\n // Update slug if provided - ensure it's in the correct format\n if (translatedContent.slug && translatedContent.slug.trim()) {\n // Check if original document has slug as an object with _type\n if (typeof originalDocument.slug === 'object' && originalDocument.slug !== null && '_type' in originalDocument.slug) {\n newDocument.slug = {\n _type: 'slug',\n current: translatedContent.slug\n };\n }\n else {\n // If original was a string or didn't exist, just use the string\n newDocument.slug = translatedContent.slug;\n }\n }\n // Convert HTML body back to portable text and merge\n // Only write to top-level body if the original had one (tracked via options)\n const shouldWriteTopLevelBody = options.bodyFoundAtTopLevel !== false;\n // DEBUG: Body handling trace\n console.log('[DocumentCreation] Body handling:', {\n hasTranslatedBody: !!translatedContent.body,\n bodyFoundAtTopLevelFromOptions: options.bodyFoundAtTopLevel,\n bodyFieldNameFromOptions: options.bodyFieldName,\n shouldWriteTopLevelBody,\n originalHasBody: 'body' in originalDocument,\n originalHasContent: 'content' in originalDocument\n });\n if (translatedContent.body && translatedContent.body.trim()) {\n const portableTextContent = this.convertHtmlToPortableText(translatedContent.body);\n if (shouldWriteTopLevelBody) {\n // Find the main content field and update it\n const contentFields = ['body', 'content', 'text', 'description'];\n let fieldWritten = false;\n for (const field of contentFields) {\n if (originalDocument[field]) {\n newDocument[field] = portableTextContent;\n console.log('[DocumentCreation] Writing body to top-level field:', field);\n fieldWritten = true;\n break;\n }\n }\n // If no content field found but we should write top-level, add to body\n if (!fieldWritten) {\n newDocument.body = portableTextContent;\n console.log('[DocumentCreation] Writing body to new top-level \"body\" field');\n }\n }\n else {\n // Body was found in nested fields - don't write to top level\n // The translated content should be handled via the fields mechanism\n console.log('[DocumentCreation] NOT writing body to top level (was found in nested field:', options.bodyFieldName, ')');\n // Remove any inherited top-level body/content fields from the spread\n const contentFields = ['body', 'content', 'text', 'description'];\n for (const field of contentFields) {\n if (field in newDocument && !(field in originalDocument)) {\n console.log('[DocumentCreation] Removing inherited top-level field:', field);\n delete newDocument[field];\n }\n }\n }\n }\n // Merge other translated fields from the fields object\n if (translatedContent.fields && typeof translatedContent.fields === 'object') {\n // First, unflatten fields with complex paths back to nested structure\n // Pass original document to preserve array structures with keyed items\n const unflattenedFields = this.unflattenFields(translatedContent.fields, originalDocument);\n for (const [fieldName, fieldValue] of Object.entries(unflattenedFields)) {\n // Skip title and slug as they're handled separately above\n if (fieldName === 'title' || fieldName === 'slug' || fieldValue === undefined) {\n continue;\n }\n // Handle the field value based on the original document's structure\n const processedValue = this.processTranslatedField(fieldName, fieldValue, originalDocument[fieldName]);\n if (processedValue !== undefined) {\n newDocument[fieldName] = processedValue;\n }\n }\n // Also handle any fields that weren't unflattened (already at top level)\n // This handles backward compatibility with non-flattened fields\n for (const [fieldPath, fieldValue] of Object.entries(translatedContent.fields)) {\n // Skip if already processed via unflatten, or if it's title/slug\n if (fieldPath === 'title' || fieldPath === 'slug' || fieldValue === undefined) {\n continue;\n }\n // Only process dotted paths directly if they weren't captured by unflatten\n // (this shouldn't normally happen, but maintains backward compatibility)\n if (fieldPath.includes('.') && !(fieldPath.split('.')[0] in unflattenedFields)) {\n const originalValue = this.getOriginalValueByPath(originalDocument, fieldPath);\n const processedValue = this.processTranslatedField(fieldPath, fieldValue, originalValue);\n if (processedValue !== undefined) {\n // Set the value at the correct nested path\n const pathParts = fieldPath.split('.');\n let current = newDocument;\n for (let i = 0; i < pathParts.length - 1; i++) {\n const part = pathParts[i];\n if (!(part in current) || current[part] === null || typeof current[part] !== 'object') {\n current[part] = {};\n }\n current = current[part];\n }\n current[pathParts[pathParts.length - 1]] = processedValue;\n }\n }\n }\n }\n // Ensure locale field is ALWAYS set on translated documents with the target language\n // This is critical for collision detection to work properly\n if (targetLang) {\n // Check if original document has locale field with {dnt, value} structure\n if (originalDocument.locale && typeof originalDocument.locale === 'object' && 'value' in originalDocument.locale) {\n newDocument.locale = {\n ...originalDocument.locale,\n value: targetLang\n };\n }\n else if (newDocument.locale && typeof newDocument.locale === 'object' && 'value' in newDocument.locale) {\n // If locale field exists in newDocument but value is empty/wrong, fix it\n newDocument.locale = {\n ...newDocument.locale,\n value: targetLang\n };\n }\n else {\n // Always set locale as a plain string if no complex structure exists\n // This ensures all translated documents have a locale field for collision detection\n newDocument.locale = targetLang;\n }\n }\n // Clean up null fields that aren't defined in the original document's schema\n // Remove fields that are explicitly null or undefined to avoid schema validation errors\n const fieldsToClean = Object.keys(newDocument);\n for (const field of fieldsToClean) {\n if (newDocument[field] === null) {\n delete newDocument[field];\n }\n }\n // Add reference to parent document if creating as variant\n if (options.createAsVariant && options.parentDocumentId) {\n newDocument.parentDocument = {\n _type: 'reference',\n _ref: options.parentDocumentId\n };\n }\n return newDocument;\n }\n /**\n * Process a translated field value and convert it to the appropriate format\n * based on the original document's structure\n */\n processTranslatedField(fieldName, translatedValue, originalValue) {\n // If translatedValue is null or undefined, return it as-is\n if (translatedValue === null || translatedValue === undefined) {\n return translatedValue;\n }\n // Extract the actual value from TranslatableField objects\n let actualValue = translatedValue;\n let isDNT = false;\n if (translatedValue && typeof translatedValue === 'object' && 'value' in translatedValue) {\n // This is a TranslatableField object - extract the value\n actualValue = translatedValue.value;\n isDNT = translatedValue.dnt || false;\n }\n // If the field is marked as DNT, use the original value instead\n if (isDNT && originalValue !== undefined) {\n return originalValue;\n }\n // Check if the original value has a specific structure that we need to preserve\n if (originalValue && typeof originalValue === 'object' && originalValue !== null) {\n // Handle fields with {dnt, value} structure\n if ('dnt' in originalValue && 'value' in originalValue) {\n // IMPORTANT: Only use actualValue if it's not empty/null/undefined\n // If actualValue is empty but translatedValue had a nested value, try to extract it\n let finalValue = actualValue;\n // Handle cases where translatedValue itself has a nested value structure\n if (translatedValue && typeof translatedValue === 'object' && 'value' in translatedValue) {\n finalValue = translatedValue.value;\n }\n // If finalValue is still empty/null/undefined, don't replace the original\n if (finalValue === null || finalValue === undefined || finalValue === '') {\n // Check if we should keep the original value\n if (originalValue.value !== null && originalValue.value !== undefined && originalValue.value !== '') {\n return originalValue;\n }\n }\n return {\n dnt: isDNT,\n value: finalValue\n };\n }\n // Handle slug objects\n if ('_type' in originalValue && originalValue._type === 'slug') {\n return {\n _type: 'slug',\n current: typeof actualValue === 'string' ? actualValue : String(actualValue)\n };\n }\n // Handle date/datetime objects\n if ('_type' in originalValue && (originalValue._type === 'date' || originalValue._type === 'datetime')) {\n return {\n _type: originalValue._type,\n value: actualValue\n };\n }\n // Handle reference objects\n if ('_type' in originalValue && originalValue._type === 'reference') {\n return originalValue; // Keep references unchanged\n }\n }\n // If the actual value is an HTML string, convert it to portable text\n if (typeof actualValue === 'string' && this.isHtmlContent(actualValue)) {\n return this.convertHtmlToPortableText(actualValue);\n }\n // Return the actual value as-is\n return actualValue;\n }\n /**\n * Convert HTML content back to Sanity portable text format\n * Requirements: 3.2, 3.4\n */\n convertHtmlToPortableText(htmlContent) {\n // This is a simplified HTML to portable text conversion\n // In a real implementation, you might want to use a proper HTML parser\n if (!htmlContent || !htmlContent.trim()) {\n return [];\n }\n const blocks = [];\n // Use a more precise regex to match complete HTML tags and their content\n const htmlTagRegex = /<(h[1-6]|p|div|blockquote|li)([^>]*)>(.*?)<\\/\\1>/gi;\n let match;\n let lastIndex = 0;\n while ((match = htmlTagRegex.exec(htmlContent)) !== null) {\n const [, tagName, , content] = match;\n // Skip if content is empty or just whitespace\n if (!content.trim()) {\n continue;\n }\n const block = {\n _type: 'block',\n _key: this.generateBlockKey(),\n style: this.getBlockStyle(tagName.toLowerCase()),\n children: this.parseInlineContent(content),\n markDefs: []\n };\n // Handle list items\n if (tagName.toLowerCase() === 'li') {\n block.listItem = 'bullet'; // Default to bullet, could be enhanced\n }\n blocks.push(block);\n lastIndex = match.index + match[0].length;\n }\n // Handle any remaining content that wasn't matched by tags\n const remainingContent = htmlContent.substring(lastIndex).trim();\n if (remainingContent) {\n // Remove any remaining HTML tags and create a block\n const cleanContent = remainingContent.replace(/<[^>]+>/g, '').trim();\n if (cleanContent) {\n blocks.push({\n _type: 'block',\n _key: this.generateBlockKey(),\n style: 'normal',\n children: this.parseInlineContent(cleanContent),\n markDefs: []\n });\n }\n }\n // If no blocks were created, create a default one with cleaned content\n if (blocks.length === 0 && htmlContent.trim()) {\n const cleanContent = htmlContent.replace(/<[^>]+>/g, '').trim();\n if (cleanContent) {\n blocks.push({\n _type: 'block',\n _key: this.generateBlockKey(),\n style: 'normal',\n children: this.parseInlineContent(cleanContent),\n markDefs: []\n });\n }\n }\n return blocks;\n }\n /**\n * Parse inline content and handle formatting\n */\n parseInlineContent(content) {\n const children = [];\n // Remove HTML tags and extract text with basic formatting\n const cleanContent = content\n .replace(/<strong[^>]*>(.*?)<\\/strong>/gi, '**$1**')\n .replace(/<em[^>]*>(.*?)<\\/em>/gi, '*$1*')\n .replace(/<u[^>]*>(.*?)<\\/u>/gi, '_$1_')\n .replace(/<code[^>]*>(.*?)<\\/code>/gi, '`$1`')\n .replace(/<[^>]+>/g, '') // Remove remaining HTML tags\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&amp;/g, '&')\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\");\n if (cleanContent.trim()) {\n children.push({\n _type: 'span',\n _key: this.generateSpanKey(),\n text: cleanContent,\n marks: []\n });\n }\n return children;\n }\n /**\n * Get block style from HTML tag name\n */\n getBlockStyle(tagName) {\n const styleMap = {\n 'h1': 'h1',\n 'h2': 'h2',\n 'h3': 'h3',\n 'h4': 'h4',\n 'h5': 'h5',\n 'h6': 'h6',\n 'blockquote': 'blockquote',\n 'p': 'normal',\n 'div': 'normal',\n 'li': 'normal'\n };\n return styleMap[tagName] || 'normal';\n }\n /**\n * Check if content appears to be HTML\n */\n isHtmlContent(content) {\n return /<[^>]+>/.test(content);\n }\n /**\n * Generate a new document ID based on original ID and target language\n */\n generateNewDocumentId(originalId, targetLanguage) {\n // Strip 'drafts.' prefix if present to generate clean base IDs\n const cleanId = originalId.startsWith('drafts.')\n ? originalId.replace(/^drafts\\./, '')\n : originalId;\n const timestamp = Date.now();\n const suffix = targetLanguage ? `-${targetLanguage}` : '-translated';\n return `${cleanId}${suffix}-${timestamp}`;\n }\n /**\n * Generate a unique key for portable text blocks\n */\n generateBlockKey() {\n return Math.random().toString(36).substr(2, 9);\n }\n /**\n * Generate a unique key for spans\n */\n generateSpanKey() {\n return Math.random().toString(36).substr(2, 9);\n }\n /**\n * Validate document structure before creation\n * Requirements: 3.4\n */\n validateDocumentStructure(document) {\n const errors = [];\n // Check required fields\n if (!document._id) {\n errors.push('Document must have an _id');\n }\n if (!document._type) {\n errors.push('Document must have a _type');\n }\n // Validate portable text fields\n const portableTextFields = ['body', 'content', 'text', 'description'];\n for (const field of portableTextFields) {\n if (document[field] && Array.isArray(document[field])) {\n const validationResult = this.validatePortableTextArray(document[field], field);\n if (!validationResult.isValid) {\n errors.push(...validationResult.errors);\n }\n }\n }\n // Validate slug format\n if (document.slug) {\n if (typeof document.slug === 'object' && document.slug !== null && '_type' in document.slug) {\n const slugObj = document.slug;\n if (slugObj._type !== 'slug') {\n errors.push('Slug object must have _type of \"slug\"');\n }\n if (!slugObj.current) {\n errors.push('Slug object must have a current value');\n }\n }\n }\n return {\n isValid: errors.length === 0,\n errors\n };\n }\n /**\n * Validate portable text array structure\n */\n validatePortableTextArray(blocks, fieldName) {\n const errors = [];\n if (!Array.isArray(blocks)) {\n errors.push(`${fieldName} must be an array`);\n return { isValid: false, errors };\n }\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i];\n if (!block || typeof block !== 'object') {\n errors.push(`${fieldName}[${i}] must be an object`);\n continue;\n }\n const blockObj = block;\n if (!blockObj._type) {\n errors.push(`${fieldName}[${i}] must have a _type`);\n }\n if (!blockObj._key) {\n errors.push(`${fieldName}[${i}] must have a _key`);\n }\n if (blockObj._type === 'block') {\n if (!Array.isArray(blockObj.children)) {\n errors.push(`${fieldName}[${i}] block must have children array`);\n }\n else {\n // Validate children\n const children = blockObj.children;\n for (let j = 0; j < children.length; j++) {\n const child = children[j];\n if (!child || typeof child !== 'object') {\n errors.push(`${fieldName}[${i}].children[${j}] must be an object`);\n continue;\n }\n const childObj = child;\n if (!childObj._type) {\n errors.push(`${fieldName}[${i}].children[${j}] must have a _type`);\n }\n if (!childObj._key) {\n errors.push(`${fieldName}[${i}].children[${j}] must have a _key`);\n }\n }\n }\n }\n }\n return {\n isValid: errors.length === 0,\n errors\n };\n }\n}\n//# sourceMappingURL=documentCreationService.js.map","/**\n * Unified Configuration Storage Adapter\n *\n * Provides centralized persistence for all plugin configuration using Sanity's document storage.\n * This replaces separate OAuth and Locale storage adapters with a single unified configuration.\n *\n * Stores in a single EL_PluginConfiguration document:\n * - OAuth configuration (projectId, accessToken)\n * - Locale definitions and settings\n * - DNT field mappings by document type\n * - Auto-translate document types for Sanity Function\n */\n/**\n * Configuration document ID for unified plugin settings\n * Internal type prefixed with EL_ to separate from customer document types\n */\nconst UNIFIED_CONFIG_DOC_ID = 'sanity-translation-plugin.config';\nconst UNIFIED_CONFIG_DOC_TYPE = 'EL_PluginConfiguration';\n/**\n * Unified configuration storage adapter for Sanity\n */\nexport class UnifiedConfigStorage {\n constructor(client) {\n this.client = client;\n }\n /**\n * Convert array-based DNT configuration (schema format) to map format (internal use)\n */\n convertDNTArrayToMap(dntConfigurations) {\n if (!dntConfigurations || !Array.isArray(dntConfigurations)) {\n return {};\n }\n const map = {};\n for (const config of dntConfigurations) {\n if (!config.documentType || !config.fields)\n continue;\n map[config.documentType] = {};\n for (const field of config.fields) {\n if (field.fieldPath) {\n map[config.documentType][field.fieldPath] = field.dnt !== false; // Default to true\n }\n }\n }\n return map;\n }\n /**\n * Convert map-based DNT configuration (internal format) to array format (schema format)\n */\n convertDNTMapToArray(dntFieldMap) {\n if (!dntFieldMap || typeof dntFieldMap !== 'object') {\n return [];\n }\n const array = [];\n for (const [documentType, fields] of Object.entries(dntFieldMap)) {\n const fieldArray = Object.entries(fields).map(([fieldPath, dnt]) => ({\n _key: `${documentType}-${fieldPath}`.replace(/[^a-zA-Z0-9-_]/g, '-'),\n fieldPath,\n dnt\n }));\n array.push({\n documentType,\n fields: fieldArray\n });\n }\n return array;\n }\n /**\n * Load complete unified configuration from Sanity\n */\n async load() {\n try {\n const doc = await this.client.fetch(`*[_id == $id][0]`, { id: UNIFIED_CONFIG_DOC_ID });\n if (!doc) {\n console.warn('No unified configuration found in Sanity');\n return null;\n }\n // Check for both old (dntFieldMap) and new (dntFieldConfigurations) formats\n let dntFieldMap = {};\n if (doc.dntFieldConfigurations) {\n // New array format - convert to map\n dntFieldMap = this.convertDNTArrayToMap(doc.dntFieldConfigurations);\n }\n else if (doc.dntFieldMap) {\n // Old map format - use directly (backward compatibility)\n dntFieldMap = doc.dntFieldMap;\n }\n // Extract config fields, excluding Sanity metadata\n const config = {\n projectId: doc.projectId,\n accessToken: doc.accessToken,\n translationApiEndpoint: doc.translationApiEndpoint,\n requestContentType: doc.requestContentType,\n responseAcceptHeader: doc.responseAcceptHeader,\n defaultDocumentCreationMode: doc.defaultDocumentCreationMode,\n collisionResolutionMode: doc.collisionResolutionMode || 'replace',\n existingDocumentHandling: doc.existingDocumentHandling || 'draft',\n locales: doc.locales || [],\n defaultLocale: doc.defaultLocale,\n dntFieldMap,\n debugMode: doc.debugMode || false,\n autoTranslateDocumentTypes: doc.autoTranslateDocumentTypes || [],\n version: doc.version || '1.0.0',\n lastUpdated: doc.lastUpdated\n };\n console.log('Loaded unified configuration from Sanity');\n return config;\n }\n catch (error) {\n console.error('Failed to load unified configuration from Sanity:', error);\n throw error;\n }\n }\n /**\n * Save complete unified configuration to Sanity\n */\n async save(config) {\n try {\n // Convert DNT map to array format for schema\n const dntFieldConfigurations = this.convertDNTMapToArray(config.dntFieldMap);\n const doc = {\n _id: UNIFIED_CONFIG_DOC_ID,\n _type: UNIFIED_CONFIG_DOC_TYPE,\n projectId: config.projectId,\n accessToken: config.accessToken,\n translationApiEndpoint: config.translationApiEndpoint,\n requestContentType: config.requestContentType,\n responseAcceptHeader: config.responseAcceptHeader,\n defaultDocumentCreationMode: config.defaultDocumentCreationMode,\n collisionResolutionMode: config.collisionResolutionMode,\n existingDocumentHandling: config.existingDocumentHandling,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n dntFieldConfigurations, // Store in schema format (array)\n debugMode: config.debugMode,\n autoTranslateDocumentTypes: config.autoTranslateDocumentTypes || [],\n version: config.version,\n lastUpdated: new Date().toISOString()\n };\n await this.client.createOrReplace(doc);\n console.log('Saved unified configuration to Sanity');\n }\n catch (error) {\n console.error('Failed to save unified configuration to Sanity:', error);\n throw error;\n }\n }\n /**\n * Update only specific fields without overwriting entire config\n */\n async update(updates) {\n try {\n const current = await this.load() || {};\n const merged = {\n ...current,\n ...updates,\n lastUpdated: new Date().toISOString()\n };\n await this.save(merged);\n }\n catch (error) {\n console.error('Failed to update unified configuration:', error);\n throw error;\n }\n }\n /**\n * Delete the unified configuration document\n */\n async delete() {\n try {\n await this.client.delete(UNIFIED_CONFIG_DOC_ID);\n console.log('Deleted unified configuration from Sanity');\n }\n catch (error) {\n console.error('Failed to delete unified configuration from Sanity:', error);\n throw error;\n }\n }\n // OAuth-specific methods\n /**\n * Load only OAuth configuration\n */\n async loadOAuth() {\n const config = await this.load();\n if (!config || !config.projectId || !config.accessToken) {\n return null;\n }\n return {\n projectId: config.projectId,\n accessToken: config.accessToken\n };\n }\n /**\n * Save OAuth configuration\n */\n async saveOAuth(oauthConfig) {\n await this.update({\n projectId: oauthConfig.projectId,\n accessToken: oauthConfig.accessToken\n });\n }\n // Locale-specific methods\n /**\n * Load only locale configuration\n */\n async loadLocale() {\n const config = await this.load();\n if (!config) {\n return null;\n }\n return {\n locales: config.locales || [],\n defaultLocale: config.defaultLocale,\n version: config.version || '1.0.0',\n lastUpdated: config.lastUpdated || new Date().toISOString()\n };\n }\n /**\n * Save locale configuration\n */\n async saveLocale(localeConfig) {\n await this.update({\n locales: localeConfig.locales,\n defaultLocale: localeConfig.defaultLocale\n });\n }\n // DNT-specific methods\n /**\n * Get DNT field map for a specific document type\n */\n async getDNTFieldsForType(documentType) {\n const config = await this.load();\n return config?.dntFieldMap?.[documentType] || {};\n }\n /**\n * Set DNT status for a field in a document type\n */\n async setDNTField(documentType, fieldPath, dnt) {\n const config = await this.load() || {};\n const dntFieldMap = config.dntFieldMap || {};\n if (!dntFieldMap[documentType]) {\n dntFieldMap[documentType] = {};\n }\n dntFieldMap[documentType][fieldPath] = dnt;\n await this.update({ dntFieldMap });\n }\n /**\n * Toggle DNT status for a field in a document type\n */\n async toggleDNTField(documentType, fieldPath) {\n const config = await this.load() || {};\n const dntFieldMap = config.dntFieldMap || {};\n if (!dntFieldMap[documentType]) {\n dntFieldMap[documentType] = {};\n }\n const currentValue = dntFieldMap[documentType][fieldPath] || false;\n dntFieldMap[documentType][fieldPath] = !currentValue;\n await this.update({ dntFieldMap });\n return dntFieldMap[documentType][fieldPath];\n }\n /**\n * Get DNT status for a specific field in a document type\n */\n async getDNTFieldStatus(documentType, fieldPath) {\n const fields = await this.getDNTFieldsForType(documentType);\n return fields[fieldPath] || false;\n }\n /**\n * Clear all DNT fields for a document type\n */\n async clearDNTFieldsForType(documentType) {\n const config = await this.load() || {};\n const dntFieldMap = config.dntFieldMap || {};\n delete dntFieldMap[documentType];\n await this.update({ dntFieldMap });\n }\n /**\n * Get all DNT field mappings\n */\n async getAllDNTFields() {\n const config = await this.load();\n return config?.dntFieldMap || {};\n }\n // Translation settings methods with fallback defaults\n /**\n * Get translation API endpoint with fallback to default\n */\n async getTranslationEndpoint() {\n const config = await this.load();\n return config?.translationApiEndpoint || 'https://app.easyling.com/_el/ext/direct/sanity';\n }\n /**\n * Get request content type with fallback to default\n */\n async getRequestContentType() {\n const config = await this.load();\n return config?.requestContentType || 'application/json';\n }\n /**\n * Get response accept header with fallback to default\n */\n async getResponseAcceptHeader() {\n const config = await this.load();\n return config?.responseAcceptHeader || 'application/json';\n }\n /**\n * Get default document creation mode with fallback to default\n */\n async getDefaultDocumentCreationMode() {\n const config = await this.load();\n return config?.defaultDocumentCreationMode || 'draft';\n }\n /**\n * Get collision resolution mode with fallback to default ('replace')\n */\n async getCollisionResolutionMode() {\n const config = await this.load();\n return config?.collisionResolutionMode || 'replace';\n }\n /**\n * Get existing document handling mode with fallback to default ('draft')\n * Only applicable when collision resolution mode is 'create'\n */\n async getExistingDocumentHandling() {\n const config = await this.load();\n return config?.existingDocumentHandling || 'draft';\n }\n /**\n * Get complete collision resolution configuration\n * Returns both the resolution mode and existing document handling settings\n */\n async getCollisionResolutionConfig() {\n const config = await this.load();\n return {\n collisionResolutionMode: config?.collisionResolutionMode || 'replace',\n existingDocumentHandling: config?.existingDocumentHandling || 'draft'\n };\n }\n /**\n * Set collision resolution configuration\n */\n async setCollisionResolutionConfig(mode, handling) {\n const updates = {\n collisionResolutionMode: mode\n };\n if (handling !== undefined) {\n updates.existingDocumentHandling = handling;\n }\n await this.update(updates);\n }\n /**\n * Get debug mode status\n */\n async getDebugMode() {\n const config = await this.load();\n return config?.debugMode || false;\n }\n /**\n * Set debug mode status\n */\n async setDebugMode(enabled) {\n await this.update({ debugMode: enabled });\n }\n // Auto-translate document types methods\n /**\n * Get auto-translate document types\n * Returns array of document type names that should be automatically translated on publish\n */\n async getAutoTranslateDocumentTypes() {\n const config = await this.load();\n return config?.autoTranslateDocumentTypes || [];\n }\n /**\n * Set auto-translate document types\n * Sets the array of document type names that should be automatically translated on publish\n */\n async setAutoTranslateDocumentTypes(types) {\n await this.update({ autoTranslateDocumentTypes: types });\n }\n}\n//# sourceMappingURL=unifiedConfigStorage.js.map","/**\n * HTML formatting utilities for content processing\n * Requirements: 3.3, 3.4 - Proper HTML formatting and special character escaping\n */\nexport class HtmlFormatter {\n /**\n * Escape HTML special characters for JSON transmission\n * Requirement 3.4: Properly escape special characters for JSON transmission\n */\n static escapeHtml(text) {\n if (typeof text !== 'string') {\n return '';\n }\n const htmlEscapeMap = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#x27;',\n '/': '&#x2F;',\n '`': '&#x60;'\n };\n return text.replace(/[&<>\"'`/]/g, (match) => htmlEscapeMap[match] || match);\n }\n /**\n * Unescape HTML entities back to regular characters\n */\n static unescapeHtml(html) {\n if (typeof html !== 'string') {\n return '';\n }\n const htmlUnescapeMap = {\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&quot;': '\"',\n '&#x27;': \"'\",\n '&#x2F;': '/',\n '&#x60;': '`'\n };\n return html.replace(/&(?:amp|lt|gt|quot|#x27|#x2F|#x60);/g, (match) => htmlUnescapeMap[match] || match);\n }\n /**\n * Format HTML content with proper structure and indentation\n * Requirement 3.2: Preserve text structure including paragraphs, lists, and formatting\n */\n static formatHtml(html, options = {}) {\n if (typeof html !== 'string') {\n return '';\n }\n const { preserveWhitespace = true, escapeSpecialChars = false, minifyOutput = false, addLineBreaks = true } = options;\n let formatted = html;\n // Escape special characters if requested\n if (escapeSpecialChars) {\n formatted = this.escapeHtml(formatted);\n }\n // Handle whitespace preservation\n if (!preserveWhitespace) {\n formatted = formatted.replace(/\\s+/g, ' ').trim();\n }\n // Add line breaks for better readability\n if (addLineBreaks && !minifyOutput) {\n formatted = formatted\n .replace(/(<\\/(?:p|div|h[1-6]|li|blockquote)>)/g, '$1\\n')\n .replace(/(<(?:p|div|h[1-6]|li|blockquote)[^>]*>)/g, '\\n$1')\n .replace(/(<br\\s*\\/?>)/g, '$1\\n')\n .replace(/\\n\\s*\\n/g, '\\n')\n .trim();\n }\n // Minify output if requested\n if (minifyOutput) {\n formatted = formatted\n .replace(/>\\s+</g, '><')\n .replace(/\\s+/g, ' ')\n .trim();\n }\n return formatted;\n }\n /**\n * Clean HTML content by removing unwanted tags and attributes\n */\n static cleanHtml(html, allowedTags = []) {\n if (typeof html !== 'string') {\n return '';\n }\n const defaultAllowedTags = [\n 'p', 'div', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'strong', 'em', 'u', 'code', 'pre', 'blockquote',\n 'ul', 'ol', 'li', 'a', 'img', 'figure', 'figcaption',\n 'time', 'br'\n ];\n const tagsToAllow = allowedTags.length > 0 ? allowedTags : defaultAllowedTags;\n const tagPattern = new RegExp(`<(?!/?(?:${tagsToAllow.join('|')})(?:\\\\s|>))[^>]+>`, 'gi');\n return html.replace(tagPattern, '');\n }\n /**\n * Wrap content in appropriate HTML structure\n * Requirement 3.3: Include HTML content in structured format\n */\n static wrapContent(content, wrapper = 'div', className) {\n if (typeof content !== 'string') {\n return '';\n }\n const classAttr = className ? ` class=\"${this.escapeHtml(className)}\"` : '';\n return `<${wrapper}${classAttr}>${content}</${wrapper}>`;\n }\n /**\n * Extract text content from HTML, removing all tags\n */\n static stripHtml(html) {\n if (typeof html !== 'string') {\n return '';\n }\n return html\n .replace(/<[^>]*>/g, '')\n .replace(/&[^;]+;/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n }\n /**\n * Validate HTML structure and check for common issues\n */\n static validateHtml(html) {\n const errors = [];\n if (typeof html !== 'string') {\n errors.push('HTML content must be a string');\n return { isValid: false, errors };\n }\n // For basic validation, we'll just check for obviously malformed tags\n // More sophisticated validation would require a proper HTML parser\n // Check for obviously malformed tags\n if (html.includes('<>') || html.includes('</>')) {\n errors.push('Malformed HTML tags detected');\n }\n // Check for unclosed angle brackets\n const openBrackets = (html.match(/</g) || []).length;\n const closeBrackets = (html.match(/>/g) || []).length;\n if (openBrackets !== closeBrackets) {\n errors.push('Mismatched angle brackets detected');\n }\n return {\n isValid: errors.length === 0,\n errors\n };\n }\n /**\n * Convert line breaks to HTML paragraphs\n */\n static lineBreaksToParagraphs(text) {\n if (typeof text !== 'string') {\n return '';\n }\n return text\n .split(/\\n\\s*\\n/)\n .filter(paragraph => paragraph.trim())\n .map(paragraph => `<p>${this.escapeHtml(paragraph.trim())}</p>`)\n .join('\\n');\n }\n /**\n * Truncate HTML content while preserving structure\n */\n static truncateHtml(html, maxLength, suffix = '...') {\n if (typeof html !== 'string' || html.length <= maxLength) {\n return html;\n }\n const textContent = this.stripHtml(html);\n if (textContent.length <= maxLength) {\n return html;\n }\n // Simple truncation that tries to preserve structure\n const truncated = html.substring(0, maxLength);\n const lastCompleteTag = truncated.lastIndexOf('>');\n if (lastCompleteTag > 0) {\n return truncated.substring(0, lastCompleteTag + 1) + suffix;\n }\n return truncated + suffix;\n }\n}\n// Export convenience functions for backward compatibility\nexport const htmlFormatter = {\n escapeHtml: HtmlFormatter.escapeHtml,\n unescapeHtml: HtmlFormatter.unescapeHtml,\n formatHtml: HtmlFormatter.formatHtml,\n cleanHtml: HtmlFormatter.cleanHtml,\n wrapContent: HtmlFormatter.wrapContent,\n stripHtml: HtmlFormatter.stripHtml,\n validateHtml: HtmlFormatter.validateHtml,\n lineBreaksToParagraphs: HtmlFormatter.lineBreaksToParagraphs,\n truncateHtml: HtmlFormatter.truncateHtml\n};\n//# sourceMappingURL=htmlFormatter.js.map","/**\n * Validation functions for document and payload structure\n * Requirements: 3.4, 4.3 - Validate document structure and provide clear error messages\n */\nexport class Validator {\n /**\n * Validate Sanity document structure\n * Requirement 3.4: Validate document structure\n */\n static validateSanityDocument(document, options = {}) {\n const errors = [];\n const warnings = [];\n const { requireTitle = false, requireContent = false, allowEmptyFields = true, maxContentLength = 1000000 // 1MB\n } = options;\n // Check if document exists\n if (!document) {\n errors.push('Document is null or undefined');\n return { isValid: false, errors, warnings };\n }\n // Check for required Sanity document fields\n if (!document._id) {\n errors.push('Document missing required _id field');\n }\n if (!document._type) {\n errors.push('Document missing required _type field');\n }\n // Validate _id format (basic Sanity ID validation)\n if (document._id && typeof document._id === 'string') {\n if (document._id.length === 0) {\n errors.push('Document _id cannot be empty');\n }\n else if (!/^[a-zA-Z0-9._-]+$/.test(document._id)) {\n warnings.push('Document _id contains unusual characters');\n }\n }\n else if (document._id) {\n errors.push('Document _id must be a string');\n }\n // Validate _type\n if (document._type && typeof document._type !== 'string') {\n errors.push('Document _type must be a string');\n }\n // Check for title if required\n if (requireTitle) {\n const titleFields = ['title', 'name', 'heading', 'label'];\n const hasTitle = titleFields.some(field => document[field] && typeof document[field] === 'string' && document[field].trim());\n if (!hasTitle) {\n errors.push('Document missing required title field');\n }\n }\n // Check for content if required\n if (requireContent) {\n const contentFields = ['body', 'content', 'text', 'description'];\n const hasContent = contentFields.some(field => {\n const value = document[field];\n return value && ((typeof value === 'string' && value.trim()) ||\n (Array.isArray(value) && value.length > 0) ||\n (typeof value === 'object' && Object.keys(value).length > 0));\n });\n if (!hasContent) {\n errors.push('Document missing required content fields');\n }\n }\n // Check for empty fields if not allowed\n if (!allowEmptyFields) {\n for (const [key, value] of Object.entries(document)) {\n if (!key.startsWith('_') && (value === null || value === undefined || value === '')) {\n warnings.push(`Document field '${key}' is empty`);\n }\n }\n }\n // Check for circular references and estimate content size\n try {\n const documentSize = JSON.stringify(document).length;\n if (documentSize > maxContentLength) {\n errors.push(`Document size (${documentSize} bytes) exceeds maximum allowed (${maxContentLength} bytes)`);\n }\n }\n catch (error) {\n if (error instanceof Error && error.message.includes('circular')) {\n errors.push('Document contains circular references');\n }\n else {\n // Re-throw if it's not a circular reference error\n throw error;\n }\n }\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n /**\n * Validate document content structure\n * Requirement 3.4: Validate extracted content structure\n */\n static validateDocumentContent(content) {\n const errors = [];\n const warnings = [];\n if (!content) {\n errors.push('Document content is null or undefined');\n return { isValid: false, errors, warnings };\n }\n // Check required fields\n if (!content.documentId) {\n errors.push('Document content missing documentId');\n }\n else if (typeof content.documentId !== 'string') {\n errors.push('Document content documentId must be a string');\n }\n if (!content.title) {\n warnings.push('Document content missing title');\n }\n else if (typeof content.title !== 'string') {\n errors.push('Document content title must be a string');\n }\n if (content.htmlContent === undefined || content.htmlContent === null) {\n errors.push('Document content missing htmlContent');\n }\n else if (typeof content.htmlContent !== 'string') {\n errors.push('Document content htmlContent must be a string');\n }\n else if (content.htmlContent.trim() === '') {\n warnings.push('Document content htmlContent is empty');\n }\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n /**\n * Validate extended document content structure\n */\n static validateExtendedDocumentContent(content) {\n const errors = [];\n const warnings = [];\n // First validate as basic document content\n const basicValidation = this.validateDocumentContent(content);\n errors.push(...basicValidation.errors);\n warnings.push(...basicValidation.warnings);\n // Additional validation for extended fields\n if (content.slug !== undefined && typeof content.slug !== 'string') {\n errors.push('Extended document content slug must be a string');\n }\n if (content.fields !== undefined) {\n if (typeof content.fields !== 'object' || content.fields === null) {\n errors.push('Extended document content fields must be an object');\n }\n else if (Array.isArray(content.fields)) {\n errors.push('Extended document content fields must be an object, not an array');\n }\n }\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n /**\n * Validate translation request payload\n * Requirement 3.4: Validate payload structure for JSON transmission\n */\n static validateTranslationPayload(payload, options = {}) {\n const errors = [];\n const warnings = [];\n const { requireMetadata = true, maxPayloadSize = 10000000, // 10MB\n validateHtmlStructure = true } = options;\n if (!payload) {\n errors.push('Translation payload is null or undefined');\n return { isValid: false, errors, warnings };\n }\n // Validate content structure\n if (!payload.content) {\n errors.push('Translation payload missing content field');\n }\n else {\n if (typeof payload.content !== 'object') {\n errors.push('Translation payload content must be an object');\n }\n else {\n // Validate content fields\n if (!payload.content.body) {\n errors.push('Translation payload content missing body field');\n }\n else if (typeof payload.content.body !== 'string') {\n errors.push('Translation payload content body must be a string');\n }\n if (!payload.content.title) {\n warnings.push('Translation payload content missing title field');\n }\n else if (typeof payload.content.title !== 'string') {\n errors.push('Translation payload content title must be a string');\n }\n if (payload.content.slug !== undefined && typeof payload.content.slug !== 'string') {\n errors.push('Translation payload content slug must be a string');\n }\n if (payload.content.fields !== undefined) {\n if (typeof payload.content.fields !== 'object' || payload.content.fields === null) {\n errors.push('Translation payload content fields must be an object');\n }\n }\n }\n }\n // Validate format\n if (!payload.format) {\n errors.push('Translation payload missing format field');\n }\n else if (payload.format !== 'html') {\n errors.push('Translation payload format must be \"html\"');\n }\n // Validate metadata if required\n if (requireMetadata) {\n if (!payload.metadata) {\n errors.push('Translation payload missing metadata field');\n }\n else {\n if (typeof payload.metadata !== 'object') {\n errors.push('Translation payload metadata must be an object');\n }\n else {\n // Check required metadata fields\n if (!payload.metadata.documentId) {\n errors.push('Translation payload metadata missing documentId');\n }\n if (!payload.metadata.documentType) {\n errors.push('Translation payload metadata missing documentType');\n }\n if (!payload.metadata.title) {\n warnings.push('Translation payload metadata missing title');\n }\n // Validate optional language fields\n if (payload.metadata.sourceLanguage && typeof payload.metadata.sourceLanguage !== 'string') {\n errors.push('Translation payload metadata sourceLanguage must be a string');\n }\n if (payload.metadata.targetLanguage && typeof payload.metadata.targetLanguage !== 'string') {\n errors.push('Translation payload metadata targetLanguage must be a string');\n }\n }\n }\n }\n // Validate HTML structure if requested\n if (validateHtmlStructure && payload.content?.body) {\n const htmlValidation = this.validateHtmlContent(payload.content.body);\n if (!htmlValidation.isValid) {\n warnings.push(...htmlValidation.errors.map(error => `HTML validation: ${error}`));\n }\n }\n // Check payload size\n try {\n const payloadSize = JSON.stringify(payload).length;\n if (payloadSize > maxPayloadSize) {\n errors.push(`Translation payload size (${payloadSize} bytes) exceeds maximum allowed (${maxPayloadSize} bytes)`);\n }\n }\n catch (error) {\n errors.push('Translation payload cannot be serialized to JSON');\n }\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n /**\n * Validate HTML content structure\n * Requirement 3.2: Validate HTML structure preservation\n */\n static validateHtmlContent(html) {\n const errors = [];\n const warnings = [];\n if (typeof html !== 'string') {\n errors.push('HTML content must be a string');\n return { isValid: false, errors, warnings };\n }\n // For basic validation, we'll just check for obviously malformed tags\n // More sophisticated validation would require a proper HTML parser\n // Check for obviously malformed tags\n if (html.includes('<>') || html.includes('</>')) {\n errors.push('Malformed HTML tags detected');\n }\n // Check for unclosed angle brackets\n const openBrackets = (html.match(/</g) || []).length;\n const closeBrackets = (html.match(/>/g) || []).length;\n if (openBrackets !== closeBrackets) {\n warnings.push('Mismatched angle brackets detected');\n }\n // Check for unescaped special characters in text content (basic check)\n const textContent = html.replace(/<[^>]*>/g, '');\n const unescapedChars = textContent.match(/[<>]/g);\n if (unescapedChars && unescapedChars.length > 0) {\n warnings.push('Unescaped special characters found in HTML text content');\n }\n // Check for empty HTML\n const strippedContent = html.replace(/<[^>]*>/g, '').trim();\n if (strippedContent === '') {\n warnings.push('HTML content appears to be empty after stripping tags');\n }\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n /**\n * Validate array of documents for bulk operations\n * Requirement 2.1: Validate multiple documents for bulk processing\n */\n static validateDocumentArray(documents, options = {}) {\n const errors = [];\n const warnings = [];\n if (!Array.isArray(documents)) {\n errors.push('Documents must be provided as an array');\n return { isValid: false, errors, warnings };\n }\n if (documents.length === 0) {\n warnings.push('Document array is empty');\n return { isValid: true, errors, warnings };\n }\n // Validate each document\n const documentIds = new Set();\n documents.forEach((document, index) => {\n const validation = this.validateSanityDocument(document, options);\n // Add index to error messages for clarity\n validation.errors.forEach(error => {\n errors.push(`Document ${index}: ${error}`);\n });\n validation.warnings.forEach(warning => {\n warnings.push(`Document ${index}: ${warning}`);\n });\n // Check for duplicate document IDs\n if (document?._id) {\n if (documentIds.has(document._id)) {\n errors.push(`Duplicate document ID found: ${document._id}`);\n }\n else {\n documentIds.add(document._id);\n }\n }\n });\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n /**\n * Validate endpoint URL\n */\n static validateEndpoint(endpoint) {\n const errors = [];\n const warnings = [];\n if (!endpoint) {\n errors.push('Endpoint URL is required');\n return { isValid: false, errors, warnings };\n }\n if (typeof endpoint !== 'string') {\n errors.push('Endpoint URL must be a string');\n return { isValid: false, errors, warnings };\n }\n // Basic URL validation\n try {\n const url = new URL(endpoint);\n if (!['http:', 'https:'].includes(url.protocol)) {\n errors.push('Endpoint URL must use HTTP or HTTPS protocol');\n }\n if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {\n warnings.push('Using localhost endpoint - ensure this is intended for development');\n }\n }\n catch (error) {\n errors.push('Invalid endpoint URL format');\n }\n return {\n isValid: errors.length === 0,\n errors,\n warnings\n };\n }\n}\n// Export convenience functions for backward compatibility\nexport const validator = {\n validateSanityDocument: Validator.validateSanityDocument,\n validateDocumentContent: Validator.validateDocumentContent,\n validateExtendedDocumentContent: Validator.validateExtendedDocumentContent,\n validateTranslationPayload: Validator.validateTranslationPayload,\n validateHtmlContent: Validator.validateHtmlContent,\n validateDocumentArray: Validator.validateDocumentArray,\n validateEndpoint: Validator.validateEndpoint\n};\n//# sourceMappingURL=validator.js.map","/**\n * Configuration module for Sanity Function\n *\n * Loads and validates configuration from Sanity dataset using UnifiedConfigStorage.\n * Configuration is shared with the Studio plugin and stored in the\n * EL_PluginConfiguration document.\n *\n * @module\n */\n\nimport type { SanityClient } from '@sanity/client';\nimport { UnifiedConfigStorage } from '@easyling/sanity-connector-shared';\nimport type { UnifiedPluginConfig } from '@easyling/sanity-connector-shared';\n\n/**\n * Thrown when the plugin configuration document is missing or invalid.\n */\nexport class ConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Validated, ready-to-use function configuration extracted from the\n * unified plugin config document.\n */\nexport interface FunctionConfig {\n /** Enabled target locale codes */\n targetLocales: string[];\n /** Source language code (optional) */\n sourceLocale?: string;\n /** OAuth project ID */\n projectId: string;\n /** OAuth access token */\n accessToken: string;\n /** Translation API endpoint */\n translationEndpoint: string;\n /** Document types to auto-translate */\n autoTranslateDocumentTypes: string[];\n /** Request content type */\n requestContentType: 'application/json' | 'application/x-protobuf';\n /** Response accept header */\n responseAcceptHeader: 'application/json' | 'application/x-protobuf';\n /** Default document creation mode */\n defaultDocumentCreationMode: 'draft' | 'published';\n}\n\n/**\n * Load the unified plugin configuration from the Sanity dataset.\n *\n * @param client - A configured Sanity client (created from `context.clientOptions`)\n * @returns The raw config document, or `null` if none exists\n */\nexport async function loadConfiguration(\n client: SanityClient,\n): Promise<UnifiedPluginConfig | null> {\n const storage = new UnifiedConfigStorage(client as any);\n return storage.load();\n}\n\n/**\n * Validate the raw config and extract the fields required by the function.\n *\n * @throws {ConfigurationError} when required fields are missing or invalid\n */\nexport function validateConfiguration(\n config: UnifiedPluginConfig | null,\n): FunctionConfig {\n if (!config) {\n throw new ConfigurationError('Configuration not found in Sanity dataset');\n }\n\n if (!config.projectId) {\n throw new ConfigurationError('Missing required field: projectId');\n }\n if (!config.accessToken) {\n throw new ConfigurationError('Missing required field: accessToken');\n }\n\n const targetLocales = (config.locales ?? [])\n .filter((locale) => locale.enabled)\n .map((locale) => locale.code);\n\n if (targetLocales.length === 0) {\n throw new ConfigurationError(\n 'No enabled target locales found in configuration',\n );\n }\n\n return {\n targetLocales,\n sourceLocale: config.defaultLocale,\n projectId: config.projectId,\n accessToken: config.accessToken,\n translationEndpoint:\n config.translationApiEndpoint ??\n 'https://app.easyling.com/_el/ext/direct/sanity',\n autoTranslateDocumentTypes: config.autoTranslateDocumentTypes ?? [],\n requestContentType: config.requestContentType ?? 'application/json',\n responseAcceptHeader: config.responseAcceptHeader ?? 'application/json',\n defaultDocumentCreationMode:\n config.defaultDocumentCreationMode ?? 'draft',\n };\n}\n","/**\n * Structured logging module for Sanity Function\n * \n * Provides structured logging with context fields for debugging and monitoring.\n * Logs are formatted as JSON for easy parsing by monitoring systems.\n */\n\n/**\n * Log levels supported by the logger\n */\nexport type LogLevel = 'info' | 'warn' | 'error';\n\n/**\n * Base context fields included in all log messages\n */\nexport interface LogContext {\n /** Document ID being processed */\n documentId?: string;\n /** Document type */\n documentType?: string;\n /** Operation being performed */\n operation?: string;\n /** Target languages for translation */\n targetLanguages?: string[];\n /** Error details if applicable */\n error?: string;\n /** Error stack trace if applicable */\n stack?: string;\n /** Additional context fields */\n [key: string]: unknown;\n}\n\n/**\n * Structured log entry\n */\ninterface LogEntry {\n /** Timestamp in ISO format */\n timestamp: string;\n /** Log level */\n level: LogLevel;\n /** Log message */\n message: string;\n /** Context fields */\n context?: LogContext;\n}\n\n/**\n * Format a log entry as JSON string\n * \n * @param level - Log level\n * @param message - Log message\n * @param context - Optional context fields\n * @returns JSON formatted log string\n */\nfunction formatLogEntry(level: LogLevel, message: string, context?: LogContext): string {\n const entry: LogEntry = {\n timestamp: new Date().toISOString(),\n level,\n message,\n ...(context && { context })\n };\n \n return JSON.stringify(entry);\n}\n\n/**\n * Log an info message\n * \n * @param message - Log message\n * @param context - Optional context fields\n */\nexport function info(message: string, context?: LogContext): void {\n console.log(formatLogEntry('info', message, context));\n}\n\n/**\n * Log a warning message\n * \n * @param message - Log message\n * @param context - Optional context fields\n */\nexport function warn(message: string, context?: LogContext): void {\n console.warn(formatLogEntry('warn', message, context));\n}\n\n/**\n * Log an error message\n * \n * @param message - Log message\n * @param context - Optional context fields\n */\nexport function error(message: string, context?: LogContext): void {\n console.error(formatLogEntry('error', message, context));\n}\n\n/**\n * Create a logger instance with default context\n * \n * Useful for maintaining consistent context across multiple log calls\n * \n * @param defaultContext - Default context fields to include in all logs\n * @returns Logger instance with bound context\n */\nexport function createLogger(defaultContext: LogContext) {\n return {\n info: (message: string, additionalContext?: LogContext) => {\n info(message, { ...defaultContext, ...additionalContext });\n },\n warn: (message: string, additionalContext?: LogContext) => {\n warn(message, { ...defaultContext, ...additionalContext });\n },\n error: (message: string, additionalContext?: LogContext) => {\n error(message, { ...defaultContext, ...additionalContext });\n }\n };\n}\n\n/**\n * Default logger instance\n */\nexport const logger = {\n info,\n warn,\n error,\n createLogger\n};\n","/**\n * Sanity Function for automatic document translation on publish\n *\n * Hooks into the document.publish lifecycle event and automatically\n * translates documents to configured target languages using the shared\n * translation services.\n *\n * @module @easyling/sanity-function-auto-translate\n */\n\nimport { createClient, type SanityClient } from '@sanity/client';\nimport {\n ContentExtractor,\n TranslationService,\n DocumentCreationService,\n UnifiedConfigStorage,\n} from '@easyling/sanity-connector-shared';\nimport type { UnifiedPluginConfig } from '@easyling/sanity-connector-shared';\nimport { loadConfiguration, validateConfiguration, ConfigurationError } from './config';\nimport type { FunctionConfig } from './config';\nimport { logger } from './logger';\n\n// ---------------------------------------------------------------------------\n// Public types – re-exported so consumers get IDE support from the bundle\n// ---------------------------------------------------------------------------\n\n/**\n * Shape of `context.clientOptions` provided by the Sanity Functions runtime.\n */\nexport interface SanityClientOptions {\n projectId: string;\n dataset: string;\n apiHost?: string;\n token?: string;\n}\n\n/**\n * The context object every Sanity Function handler receives.\n */\nexport interface FunctionContext {\n clientOptions: SanityClientOptions;\n /** `true` when running locally via the Sanity CLI */\n local?: boolean;\n eventResourceType?: string;\n eventResourceId?: string;\n functionResourceType?: string;\n functionResourceId?: string;\n}\n\n/**\n * The event payload for a `document.publish` trigger.\n * `data` contains the full published Sanity document.\n */\nexport interface PublishEvent {\n data: SanityDocument;\n}\n\n/** Minimal Sanity document shape. */\nexport interface SanityDocument {\n _id: string;\n _type: string;\n _createdAt: string;\n _updatedAt: string;\n _rev: string;\n [key: string]: unknown;\n}\n\n/** Translation result for a single locale. */\nexport interface TranslationResult {\n locale: string | undefined;\n documentId?: string;\n success: boolean;\n error?: string;\n}\n\n/** Metrics for tracking function execution. */\nexport interface ExecutionMetrics {\n totalInvocations: number;\n successfulTranslations: number;\n failedTranslations: number;\n skippedTranslations: number;\n localeMetrics: Record<string, { successCount: number; failureCount: number }>;\n errorsByStage: {\n configurationLoad?: number;\n configurationValidation?: number;\n contentExtraction?: number;\n translationService?: number;\n documentCreation?: number;\n timeout?: number;\n sizeLimit?: number;\n other?: number;\n };\n}\n\n/** Value returned by the function handler. */\nexport interface TranslateOnPublishResult {\n success: boolean;\n skipped?: boolean;\n reason?: string;\n error?: string;\n results?: TranslationResult[];\n summary?: {\n successCount: number;\n failureCount: number;\n totalCount: number;\n partial?: boolean;\n reason?: string;\n };\n elapsedMs?: number;\n documentSizeBytes?: number;\n limitBytes?: number;\n translationCompleted?: boolean;\n metrics: ExecutionMetrics;\n}\n\n// Re-export config types for external consumers\nexport type { FunctionConfig } from './config';\nexport type { LogLevel, LogContext } from './logger';\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst EXECUTION_DEADLINE_MS = 120_000;\nconst WARNING_THRESHOLD_MS = 100_000;\nconst TERMINATION_THRESHOLD_MS = 110_000;\nconst DOCUMENT_SIZE_LIMIT_BYTES = 10 * 1024 * 1024; // 10 MB\n\nfunction checkDeadline(\n startTime: number,\n log: ReturnType<typeof logger.createLogger>,\n): { warning: boolean; shouldTerminate: boolean; elapsed: number } {\n const elapsed = Date.now() - startTime;\n const warning = elapsed > WARNING_THRESHOLD_MS;\n const shouldTerminate = elapsed > TERMINATION_THRESHOLD_MS;\n\n if (shouldTerminate) {\n log.error('Execution deadline approaching – terminating gracefully', {\n elapsedMs: elapsed,\n deadlineMs: EXECUTION_DEADLINE_MS,\n thresholdMs: TERMINATION_THRESHOLD_MS,\n });\n } else if (warning) {\n log.warn('Execution time approaching deadline', {\n elapsedMs: elapsed,\n deadlineMs: EXECUTION_DEADLINE_MS,\n warningThresholdMs: WARNING_THRESHOLD_MS,\n });\n }\n\n return { warning, shouldTerminate, elapsed };\n}\n\n/**\n * Determine whether a document should be auto-translated.\n * An empty or missing autoTranslateDocumentTypes list means all types are eligible.\n */\nexport function shouldTranslate(\n document: SanityDocument,\n config: FunctionConfig,\n): boolean {\n if (!document?._type) return false;\n if (!config.autoTranslateDocumentTypes?.length) return true;\n return config.autoTranslateDocumentTypes.includes(document._type);\n}\n\n/**\n * Build a `SanityClient` from the runtime-provided client options.\n */\nfunction buildClient(options: SanityClientOptions): SanityClient {\n return createClient({\n ...options,\n apiVersion: '2025-05-08',\n useCdn: false,\n }) as unknown as SanityClient;\n}\n\n// ---------------------------------------------------------------------------\n// Main handler\n// ---------------------------------------------------------------------------\n\n/**\n * Entry-point for the Sanity Function.\n *\n * Called by the Sanity Functions runtime on every `document.publish` event.\n */\nexport default async function translateOnPublish(\n event: PublishEvent,\n context: FunctionContext,\n): Promise<TranslateOnPublishResult> {\n const startTime = Date.now();\n\n const metrics: ExecutionMetrics = {\n totalInvocations: 1,\n successfulTranslations: 0,\n failedTranslations: 0,\n skippedTranslations: 0,\n localeMetrics: {},\n errorsByStage: {},\n };\n\n const document = event.data;\n const client = buildClient(context.clientOptions);\n\n const log = logger.createLogger({\n documentId: document._id,\n documentType: document._type,\n operation: 'translateOnPublish',\n });\n\n log.info('Function invoked', {\n documentId: document._id,\n documentType: document._type,\n startTime,\n });\n\n try {\n // ---- Configuration ----\n if (!context.clientOptions.token) {\n log.warn('No auth token in clientOptions – the client cannot read non-public documents. ' +\n 'If running locally, use --with-user-token or enable \"With Token\" in the dev playground.');\n }\n log.info('Loading configuration from Sanity dataset');\n const rawConfig = await loadConfiguration(client);\n\n let config: FunctionConfig;\n try {\n config = validateConfiguration(rawConfig);\n log.info('Configuration validated', {\n targetLocales: config.targetLocales,\n autoTranslateDocumentTypes: config.autoTranslateDocumentTypes,\n });\n } catch (error) {\n metrics.errorsByStage.configurationValidation =\n (metrics.errorsByStage.configurationValidation ?? 0) + 1;\n log.error('Configuration validation failed', {\n error: error instanceof Error ? error.message : String(error),\n metrics,\n });\n throw error;\n }\n\n // ---- Document-type gate ----\n if (!shouldTranslate(document, config)) {\n metrics.skippedTranslations++;\n log.info('Document type not configured for auto-translation', {\n documentType: document._type,\n configuredTypes: config.autoTranslateDocumentTypes,\n metrics,\n });\n return {\n success: true,\n skipped: true,\n reason: 'Document type not in autoTranslateDocumentTypes',\n metrics,\n };\n }\n\n // ---- Locale gate ----\n const { targetLocales } = config;\n if (targetLocales.length === 0) {\n metrics.errorsByStage.configurationValidation =\n (metrics.errorsByStage.configurationValidation ?? 0) + 1;\n log.error('No enabled target locales found', { metrics });\n throw new ConfigurationError('No enabled target locales found in configuration');\n }\n\n // ---- Size gate ----\n const documentSizeBytes = JSON.stringify(document).length;\n if (documentSizeBytes > DOCUMENT_SIZE_LIMIT_BYTES) {\n metrics.skippedTranslations++;\n metrics.errorsByStage.sizeLimit = (metrics.errorsByStage.sizeLimit ?? 0) + 1;\n log.warn('Document exceeds size limit – skipping translation', {\n documentSizeBytes,\n limitBytes: DOCUMENT_SIZE_LIMIT_BYTES,\n metrics,\n });\n return {\n success: true,\n skipped: true,\n reason: 'Document exceeds size limit',\n documentSizeBytes,\n limitBytes: DOCUMENT_SIZE_LIMIT_BYTES,\n metrics,\n };\n }\n\n log.info('Starting translation workflow', {\n targetLocales,\n sourceLocale: config.sourceLocale,\n });\n\n // ---- Deadline check: before content extraction ----\n let deadlineCheck = checkDeadline(startTime, log);\n if (deadlineCheck.shouldTerminate) {\n metrics.skippedTranslations++;\n metrics.errorsByStage.timeout = (metrics.errorsByStage.timeout ?? 0) + 1;\n return {\n success: true,\n skipped: true,\n reason: 'Execution deadline approaching',\n elapsedMs: deadlineCheck.elapsed,\n metrics,\n };\n }\n\n // ---- Content extraction ----\n log.info('Extracting document content');\n const extractor = new ContentExtractor();\n let content;\n try {\n content = await extractor.extractStructuredContent(document as any);\n log.info('Content extracted successfully', {\n hasTitle: !!content.title,\n hasHtmlContent: !!content.htmlContent,\n fieldCount: Object.keys(content.fields ?? {}).length,\n });\n } catch (error) {\n metrics.errorsByStage.contentExtraction =\n (metrics.errorsByStage.contentExtraction ?? 0) + 1;\n log.error('Content extraction failed', {\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n metrics,\n });\n throw error;\n }\n\n // ---- Translation ----\n log.info('Initializing translation service', {\n endpoint: config.translationEndpoint,\n requestContentType: config.requestContentType,\n responseAcceptHeader: config.responseAcceptHeader,\n });\n\n const translationService = new TranslationService(\n config.translationEndpoint,\n config.requestContentType,\n config.responseAcceptHeader,\n );\n translationService.setAuthToken(config.accessToken, config.projectId);\n\n deadlineCheck = checkDeadline(startTime, log);\n if (deadlineCheck.shouldTerminate) {\n metrics.skippedTranslations++;\n metrics.errorsByStage.timeout = (metrics.errorsByStage.timeout ?? 0) + 1;\n return {\n success: true,\n skipped: true,\n reason: 'Execution deadline approaching before translation',\n elapsedMs: deadlineCheck.elapsed,\n metrics,\n };\n }\n\n log.info('Sending translation request', { targetLocales, sourceLocale: config.sourceLocale });\n\n let response;\n try {\n response = await translationService.translateDocument(\n content,\n document._type,\n config.sourceLocale,\n undefined,\n targetLocales,\n );\n\n if (!response.success) {\n metrics.failedTranslations++;\n metrics.errorsByStage.translationService =\n (metrics.errorsByStage.translationService ?? 0) + 1;\n log.error('Translation request failed', {\n error: response.error,\n requestId: response.requestId,\n metrics,\n });\n throw new Error(`Translation request failed: ${response.error ?? 'unknown error'}`);\n }\n\n log.info('Translation completed successfully', {\n translatedDocumentCount: response.translatedDocuments?.length ?? 0,\n requestId: response.requestId,\n });\n } catch (error) {\n metrics.failedTranslations++;\n metrics.errorsByStage.translationService =\n (metrics.errorsByStage.translationService ?? 0) + 1;\n log.error('Translation service call failed', {\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n metrics,\n });\n throw error;\n }\n\n // ---- Document creation ----\n let creationService;\n try {\n creationService = new DocumentCreationService(client as any, config.defaultDocumentCreationMode);\n } catch (error) {\n metrics.errorsByStage.documentCreation =\n (metrics.errorsByStage.documentCreation ?? 0) + 1;\n log.error('Failed to initialize DocumentCreationService', {\n error: error instanceof Error ? error.message : String(error),\n metrics,\n });\n throw error;\n }\n\n const results: TranslationResult[] = [];\n\n deadlineCheck = checkDeadline(startTime, log);\n if (deadlineCheck.shouldTerminate) {\n metrics.skippedTranslations++;\n metrics.errorsByStage.timeout = (metrics.errorsByStage.timeout ?? 0) + 1;\n return {\n success: true,\n skipped: true,\n reason: 'Execution deadline approaching before document creation',\n elapsedMs: deadlineCheck.elapsed,\n translationCompleted: true,\n metrics,\n };\n }\n\n for (const translatedDoc of response.translatedDocuments ?? []) {\n const targetLocale = translatedDoc.locale;\n\n if (targetLocale && !metrics.localeMetrics[targetLocale]) {\n metrics.localeMetrics[targetLocale] = { successCount: 0, failureCount: 0 };\n }\n\n deadlineCheck = checkDeadline(startTime, log);\n if (deadlineCheck.shouldTerminate) {\n metrics.errorsByStage.timeout = (metrics.errorsByStage.timeout ?? 0) + 1;\n metrics.successfulTranslations = results.filter((r) => r.success).length;\n metrics.failedTranslations = results.filter((r) => !r.success).length;\n\n return {\n success: true,\n results,\n summary: {\n successCount: results.filter((r) => r.success).length,\n failureCount: results.filter((r) => !r.success).length,\n totalCount: results.length,\n partial: true,\n reason: 'Execution deadline approaching',\n },\n elapsedMs: deadlineCheck.elapsed,\n metrics,\n };\n }\n\n log.info('Creating translated document', {\n targetLocale,\n parentDocumentId: document._id,\n });\n\n try {\n const result = await creationService.createDocumentFromTranslation(\n document as any,\n { ...response, translatedDocuments: [translatedDoc] },\n {\n targetLanguage: targetLocale,\n parentDocumentId: document._id,\n creationMode: config.defaultDocumentCreationMode,\n },\n );\n\n if (result.success) {\n metrics.successfulTranslations++;\n if (targetLocale) metrics.localeMetrics[targetLocale].successCount++;\n log.info('Translated document created successfully', {\n targetLocale,\n documentId: result.documentId,\n slugFallback: result.slugFallback,\n });\n results.push({ locale: targetLocale, documentId: result.documentId, success: true });\n } else {\n metrics.failedTranslations++;\n metrics.errorsByStage.documentCreation =\n (metrics.errorsByStage.documentCreation ?? 0) + 1;\n if (targetLocale) metrics.localeMetrics[targetLocale].failureCount++;\n log.error('Failed to create translated document', {\n targetLocale,\n error: result.error,\n metrics,\n });\n results.push({ locale: targetLocale, success: false, error: result.error });\n }\n } catch (error) {\n metrics.failedTranslations++;\n metrics.errorsByStage.documentCreation =\n (metrics.errorsByStage.documentCreation ?? 0) + 1;\n if (targetLocale) metrics.localeMetrics[targetLocale].failureCount++;\n log.error('Exception while creating translated document', {\n targetLocale,\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n metrics,\n });\n results.push({\n locale: targetLocale,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n const failureCount = results.filter((r) => !r.success).length;\n const finalElapsed = Date.now() - startTime;\n\n if (successCount === 0 && failureCount > 0) {\n log.error('Translation workflow failed – all locales failed', {\n totalResults: results.length,\n failureCount,\n elapsedMs: finalElapsed,\n metrics,\n });\n throw new Error(\n `Translation failed for all ${failureCount} locale(s): ` +\n results.map((r) => `${r.locale}: ${r.error}`).join('; '),\n );\n }\n\n const workflowLogLevel = failureCount > 0 ? 'warn' : 'info';\n log[workflowLogLevel]('Translation workflow completed', {\n totalResults: results.length,\n successCount,\n failureCount,\n elapsedMs: finalElapsed,\n metrics,\n });\n\n return {\n success: failureCount === 0,\n results,\n summary: { successCount, failureCount, totalCount: results.length },\n elapsedMs: finalElapsed,\n metrics,\n };\n } catch (error) {\n metrics.failedTranslations++;\n metrics.errorsByStage.other = (metrics.errorsByStage.other ?? 0) + 1;\n log.error('Translation workflow failed with exception', {\n error: error instanceof Error ? error.message : String(error),\n stack: error instanceof Error ? error.stack : undefined,\n metrics,\n });\n throw error;\n }\n}\n"],"names":["__importDefault","this","mod","__esModule","Object","defineProperty","exports","value","Metadata","TranslatableField","Content_FieldsEntry","Content","TranslationRequestPayload","protobufPackage","minimal_1","isSet","encode","message","writer","default","Writer","create","undefined","content","uint32","fork","ldelim","project","string","format","metadata","decode","input","length","reader","Reader","end","len","pos","tag","skipType","fromJSON","object","globalThis","String","toJSON","obj","base","fromPartial","body","title","slug","entries","fields","forEach","key","entry4","reduce","acc","k","v","dnt","bool","type","path","Boolean","documentId","documentType","sourceLanguage","targetLanguage","targetLocales","push","Array","isArray","map","e","TranslatedDocument_FieldsEntry","TranslatedDocument","TranslationResponse","translation_request_1","success","translatedDocuments","sourceLocale","error","requestId","locale","module","fn","ctx","params","arguments","offset","index","pending","Promise","resolve","reject","err","apply","base64","p","n","charAt","Math","ceil","b64","s64","i","buffer","start","t","parts","chunk","j","b","fromCharCode","slice","join","invalidEncoding","c","charCodeAt","Error","test","EventEmitter","_listeners","prototype","on","evt","off","listeners","splice","emit","args","factory","Float32Array","f32","f8b","Uint8Array","le","writeFloat_f32_cpy","val","buf","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","writeFloat_ieee754","writeUint","sign","isNaN","round","exponent","floor","log","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","f64","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","inquire","moduleName","eval","replace","keys","alloc","size","SIZE","MAX","slab","call","utf8","read","write","c1","c2","protobuf","configure","util","_configure","BufferWriter","BufferReader","build","rpc","roots","LongBits","indexOutOfRange","writeLength","RangeError","create_array","Buffer","isBuffer","readLongVarint","bits","readFixed32_end","readFixed64","_slice","subarray","int32","sint32","fixed32","sfixed32","float","double","bytes","nativeBuffer","constructor","skip","wireType","BufferReader_","Long","merge","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","toString","Service","rpcImpl","requestDelimited","responseDelimited","TypeError","rpcCall","method","requestCtor","responseCtor","request","callback","self","asPromise","finish","response","setTimeout","endedByRPC","zero","toNumber","zzEncode","zeroHash","fromNumber","from","isString","parseInt","fromString","low","high","unsigned","toLong","fromHash","hash","toHash","mask","part0","part1","part2","dst","src","ifNotSet","newError","name","CustomError","properties","get","captureStackTrace","stack","writable","enumerable","configurable","set","pool","isNode","global","process","versions","node","window","emptyArray","freeze","emptyObject","isInteger","Number","isFinite","isObject","isset","prop","hasOwnProperty","utf8Write","_Buffer_from","_Buffer_allocUnsafe","newBuffer","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","lcFirst","str","toLowerCase","substring","ProtocolError","oneOfGetter","fieldNames","fieldMap","oneOfSetter","toJSONOptions","longs","enums","json","encoding","allocUnsafe","Op","next","noop","State","head","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","reset","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","d","definition","o","computeDNTDefault","context","DNT_FIELD_NAME_PATTERNS","DNT_GROUP_NAME_PATTERNS","fieldType","includes","shouldBeDNT","reason","fieldNameLower","fieldName","pattern","groupName","groupNameLower","fieldsetName","fieldsetNameLower","ATOMIC_SANITY_TYPES","Set","buildGroqPath","documentContext","fieldPath","ContentExtractor","inferSanityType","_type","isSanitySpecialType","has","shouldFlattenObject","flattenObjectToFields","basePath","docContext","startsWith","flattenArrayToFields","addLeafField","array","every","item","extractedValue","processArray","defaultDNT","JSON","stringify","_key","itemPath","current","dateValue","extractDocumentContent","document","_id","convertToHtml","html","processField","trim","extractStructuredContent","dntStorage","foundAtTopLevel","titleFoundAtTopLevel","extractTitle","extractSlug","bodyContent","bodyFoundAtTopLevel","bodyFieldName","separateContentAndFields","console","extractedTitle","documentHasTopLevelTitle","documentHasTopLevelBody","enhancedFields","applyDNTPreferences","htmlContent","fieldContextMap","storedDntFields","getFieldsForType","fieldValue","split","pop","hasStoredPreference","extractionDnt","isDNT","typedField","warn","extractBulkContent","documents","results","extractBulkStructuredContent","structuredContent","processObject","wrapInHtml","listItem","listType","processPortableTextBlockContent","processPortableTextBlock","block","style","children","child","text","marks","mark","href","escapeHtml","_ref","alt","caption","asset","lat","lng","Date","toLocaleDateString","hex","alpha","contentFields","metadataFields","nestedBody","findBodyInNestedFields","contentField","nestedPath","found","itemBasePath","slugFields","field","titleFields","nestedTitle","findTitleInNestedFields","titleField","htmlEscapeMap","char","TranslationService","placeholderEndpoint","requestContentType","responseAcceptHeader","setAuthToken","token","projectId","accessToken","clearAuth","setConfiguration","endpoint","convertPayloadToProtobuf","payload","protoFields","protoPayload","convertPayloadToProtobufJSON","normalizeTranslatedFields","normalizedFields","convertProtobufBinaryToResponse","binaryData","protoResponse","doc","protoField","parsedValue","parse","convertProtobufJSONToResponse","jsonData","originalDoc","originalValue","prepareTranslationRequest","translatableFields","fromContent","willUse","translateDocument","sendTranslationRequest","logTranslationRequest","headers","protobufJSON","fetch","ok","status","arrayBuffer","data","protoError","translations","translation","translatedContent","targetLocale","timestamp","toISOString","processBulkTranslation","contents","summary","totalDocuments","processedDocuments","failedDocuments","requests","responses","localeCount","logBulkTranslationSummary","successRate","toFixed","setEndpoint","getEndpoint","CollisionDetectionError","code","details","super","CollisionDetectionService","client","detectCollision","options","sourceDocumentId","cleanSourceId","parentMatch","findByParentReference","detected","existingDocument","matchedBy","slugMatch","findBySlugAndLocale","typeFilter","queryWithLocale","queryWithIdPattern","sourceId","sourceIdWithDrafts","idPattern","result","detectBulkCollisions","Map","DocumentCreationService","defaultCreationMode","collisionDetectionService","defaultCollisionResolutionMode","defaultExistingDocumentHandling","setDefaultCreationMode","mode","setDefaultCollisionResolutionMode","setDefaultExistingDocumentHandling","handling","setCollisionResolutionConfig","replaceExistingDocument","newDocument","creationMode","existingId","isExistingDraft","documentToSave","_createdAt","_rev","_updatedAt","replacedDocument","createOrReplace","draftId","draftDoc","publishedId","publishedDoc","handleExistingDocument","delete","createDocumentFromTranslation","originalDocument","translationResponse","inputValidation","validateInputsForDocumentCreation","isValid","errors","titleFoundAtTopLevelFromOptions","translatedContentKeys","responseValidation","validateTranslationResponseForCreation","mergeTranslatedContent","validationResult","validateDocumentStructure","businessValidation","validateBusinessRules","slugFallbackInfo","slugNeedsFallback","originalSlug","fallbackSlug","effectiveCreationMode","effectiveCollisionMode","collisionResolutionMode","effectiveExistingDocHandling","existingDocumentHandling","collisionInfo","collisionResult","parentDocumentId","translatedSlug","collisionDetected","existingDocumentId","replaceResult","resolutionAction","existingDocumentAction","slugFallback","handleResult","createdDocument","sanityError","formatErrorMessage","createAsVariant","documentHasContent","newSlug","hasContentInNestedFields","baseMessage","contextInfo","createBulkDocumentsFromTranslations","originalDocuments","translationResponses","successfulCreations","failedCreations","rollbackInfo","canRollback","createdDocumentIds","rollbackInstructions","slugFallbacks","validationErrors","validateBulkTranslationResponses","createdDocuments","preCreationValidation","singleDocumentResponse","creationResult","originalId","errorMessage","id","fallback","createRollbackPlan","parseFieldPath","segments","groqPrefixMatch","match","cleanPath","segmentRegex","exec","propertyName","keyValue","lastIndex","unflattenFields","fieldKey","actualValue","endsWith","isHtmlContent","convertHtmlToPortableText","originalCurrent","segment","isLastSegment","arrayItem","find","originalItem","assign","getOriginalValueByPath","pathParts","part","targetLang","generateNewDocumentId","shouldWriteTopLevelTitle","originalDocumentTitle","originalDocumentHasTitle","translatedContentTitle","newDocumentTitleBefore","hasTitle","titleNotEmpty","shouldWriteTopLevelBody","hasTranslatedBody","bodyFoundAtTopLevelFromOptions","bodyFieldNameFromOptions","originalHasBody","originalHasContent","portableTextContent","fieldWritten","unflattenedFields","processedValue","processTranslatedField","fieldsToClean","parentDocument","translatedValue","finalValue","blocks","htmlTagRegex","tagName","generateBlockKey","getBlockStyle","parseInlineContent","markDefs","remainingContent","cleanContent","generateSpanKey","now","random","substr","portableTextFields","validatePortableTextArray","slugObj","blockObj","childObj","UNIFIED_CONFIG_DOC_ID","UNIFIED_CONFIG_DOC_TYPE","UnifiedConfigStorage","convertDNTArrayToMap","dntConfigurations","config","convertDNTMapToArray","dntFieldMap","fieldArray","load","dntFieldConfigurations","translationApiEndpoint","defaultDocumentCreationMode","locales","defaultLocale","debugMode","autoTranslateDocumentTypes","version","lastUpdated","save","update","updates","merged","loadOAuth","saveOAuth","oauthConfig","loadLocale","saveLocale","localeConfig","getDNTFieldsForType","setDNTField","toggleDNTField","currentValue","getDNTFieldStatus","clearDNTFieldsForType","getAllDNTFields","getTranslationEndpoint","getRequestContentType","getResponseAcceptHeader","getDefaultDocumentCreationMode","getCollisionResolutionMode","getExistingDocumentHandling","getCollisionResolutionConfig","getDebugMode","setDebugMode","enabled","getAutoTranslateDocumentTypes","setAutoTranslateDocumentTypes","types","HtmlFormatter","unescapeHtml","htmlUnescapeMap","formatHtml","preserveWhitespace","escapeSpecialChars","minifyOutput","addLineBreaks","formatted","cleanHtml","allowedTags","tagsToAllow","tagPattern","RegExp","wrapContent","wrapper","className","stripHtml","validateHtml","lineBreaksToParagraphs","filter","paragraph","truncateHtml","maxLength","suffix","truncated","lastCompleteTag","lastIndexOf","htmlFormatter","Validator","validateSanityDocument","warnings","requireTitle","requireContent","allowEmptyFields","maxContentLength","some","documentSize","validateDocumentContent","validateExtendedDocumentContent","basicValidation","validateTranslationPayload","requireMetadata","maxPayloadSize","validateHtmlStructure","htmlValidation","validateHtmlContent","payloadSize","unescapedChars","validateDocumentArray","documentIds","validation","warning","add","validateEndpoint","url","URL","protocol","hostname","validator","ConfigurationError","async","loadConfiguration","validateConfiguration","translationEndpoint","formatLogEntry","level","entry","info","createLogger","defaultContext","additionalContext","logger","EXECUTION_DEADLINE_MS","WARNING_THRESHOLD_MS","TERMINATION_THRESHOLD_MS","DOCUMENT_SIZE_LIMIT_BYTES","checkDeadline","startTime","elapsed","shouldTerminate","elapsedMs","deadlineMs","thresholdMs","warningThresholdMs","shouldTranslate","buildClient","apiVersion","useCdn","translateOnPublish","event","metrics","totalInvocations","successfulTranslations","failedTranslations","skippedTranslations","localeMetrics","errorsByStage","clientOptions","operation","rawConfig","configurationValidation","configuredTypes","skipped","documentSizeBytes","sizeLimit","limitBytes","deadlineCheck","timeout","extractor","hasHtmlContent","fieldCount","contentExtraction","translationService","creationService","translatedDocumentCount","documentCreation","translationCompleted","translatedDoc","successCount","failureCount","r","totalCount","partial","finalElapsed","totalResults","other"],"sourceRoot":""}