AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(word-documents): fill Word templates (#16779)
Kishan Parmar6f4be340d7c4
diff --git a/bun.lock b/bun.lockindex 0c08778254b..6f6eeb160b5 100644--- a/bun.lock+++ b/bun.lock@@ -10922,13 +10922,15 @@},"packages/pieces/core/word-documents": {"name": "@activepieces/piece-word-documents",- "version": "0.0.1",+ "version": "0.0.2","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*","@activepieces/pieces-common": "workspace:*","@activepieces/pieces-framework": "workspace:*",+ "docxtemplater": "3.71.1","officeparser": "8.1.1",+ "pizzip": "3.3.0",},"devDependencies": {"tslib": "2.6.2",@@ -15755,6 +15757,8 @@"docusign-esign": ["[email protected]", "", { "dependencies": { "@devhigley/parse-proxy": "^1.0.3", "axios": "^1.6.8", "csv-stringify": "^1.0.0", "jsonwebtoken": "^9.0.0", "passport-oauth2": "^1.6.1", "safe-buffer": "^5.1.2" } }, "sha512-p+YgSlAv5OspREJT6NvgEZMR5L8j1SGMZRUM2NEVvdcW35dmklB3Kx2ia8SrKfq5/U9sTSEiSQJiphKQGBgU0w=="],+ "docxtemplater": ["[email protected]", "", { "dependencies": { "@xmldom/xmldom": "^0.9.12" } }, "sha512-lXX1FNYwwe/md6WYmNE/1MRjbGN3h0SFdVxKQ3fiIRFvKp0TqgJinylu144iWwPJeALa36jmgGKxk54bGx7bSA=="],+"dom-accessibility-api": ["[email protected]", "", {}, "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg=="],"dom-helpers": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.8.7", "csstype": "^3.0.2" } }, "sha512-nRCa7CK3VTrM2NmGkIy4cbK7IZlgBE/PYMn55rrXefr5xXDP0LdtfPnblFDoVdcAfslJ7or6iqAUnx0CCGIWQA=="],@@ -17341,6 +17345,8 @@"pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^3.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-J8B6xqiO37sU/gkcMglv6h5Jbd9xNER7aHzpfRdNmV4IbQBzBpe4l9XmbG+xPF/znacgu2jfEw+wHffaq/YkXA=="],+ "pizzip": ["[email protected]", "", { "dependencies": { "pako": "^2.1.0" } }, "sha512-seR2ALUYS4Z0GCs0sVwXWImhBsoCImXpHr+ExNfIZ9G0czvHqpUxlJgwHCl1BBHFyU3nUFmZJPFEEWbpY8cKRg=="],+"pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],"pkg-dir": ["[email protected]", "", { "dependencies": { "find-up": "^4.0.0" } }, "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ=="],@@ -19543,6 +19549,8 @@"docusign-esign/csv-stringify": ["[email protected]", "", { "dependencies": { "lodash.get": "~4.4.2" } }, "sha512-3NmNhhd+AkYs5YtM1GEh01VR6PKj6qch2ayfQaltx5xpcAdThjnbbI5eT8CzRVpXfGKAxnmrSYLsNl/4f3eWiw=="],+ "docxtemplater/@xmldom/xmldom": ["@xmldom/[email protected]", "", {}, "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A=="],+"dom-helpers/@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g=="],"dom-serializer/entities": ["[email protected]", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],diff --git a/packages/pieces/core/word-documents/.eslintrc.json b/packages/pieces/core/word-documents/.eslintrc.jsonindex 01f1c80f85a..66fcde330e2 100644--- a/packages/pieces/core/word-documents/.eslintrc.json+++ b/packages/pieces/core/word-documents/.eslintrc.json@@ -1,25 +1,13 @@{- "extends": [- "../../../../.eslintrc.base.json"- ],- "ignorePatterns": [- "!**/*"- ],+ "extends": ["../../../../.eslintrc.base.json"],+ "ignorePatterns": ["!**/*"],"overrides": [{- "files": [- "*.ts",- "*.tsx",- "*.js",- "*.jsx"- ],+ "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],"rules": {}},{- "files": [- "*.ts",- "*.tsx"- ],+ "files": ["*.ts", "*.tsx"],"rules": {"no-restricted-imports": ["error",@@ -37,10 +25,7 @@}},{- "files": [- "*.js",- "*.jsx"- ],+ "files": ["*.js", "*.jsx"],"rules": {}}]diff --git a/packages/pieces/core/word-documents/package.json b/packages/pieces/core/word-documents/package.jsonindex ba711e4c150..1a47badbfee 100644--- a/packages/pieces/core/word-documents/package.json+++ b/packages/pieces/core/word-documents/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-word-documents",- "version": "0.0.1",+ "version": "0.0.2","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {@@ -8,7 +8,9 @@"@activepieces/pieces-framework": "workspace:*","@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",- "officeparser": "8.1.1"+ "officeparser": "8.1.1",+ "docxtemplater": "3.71.1",+ "pizzip": "3.3.0"},"devDependencies": {"vitest": "3.2.6",diff --git a/packages/pieces/core/word-documents/src/i18n/translation.json b/packages/pieces/core/word-documents/src/i18n/translation.jsonindex 062a430cf74..19babe8703e 100644--- a/packages/pieces/core/word-documents/src/i18n/translation.json+++ b/packages/pieces/core/word-documents/src/i18n/translation.json@@ -1,11 +1,23 @@{- "Read Word documents (.docx) in your flow, no Microsoft account needed.": "Read Word documents (.docx) in your flow, no Microsoft account needed.",+ "Read Word documents (.docx) and fill Word templates in your flow, no Microsoft account needed.": "Read Word documents (.docx) and fill Word templates in your flow, no Microsoft account needed.","Extract Text": "Extract Text",+ "Fill Template": "Fill Template","Get the text, headers and footers of a Word document (.docx).": "Get the text, headers and footers of a Word document (.docx).",+ "Fill the {{placeholders}} in a Word template (.docx) and get a new document.": "Fill the {{placeholders}} in a Word template (.docx) and get a new document.","Word Document": "Word Document","Password": "Password",+ "Markdown": "Markdown",+ "Word Template": "Word Template",+ "Fields": "Fields",+ "Data (JSON)": "Data (JSON)",+ "File Name": "File Name","Pick a .docx file from an earlier step, such as an email attachment, or paste a URL to download.": "Pick a .docx file from an earlier step, such as an email attachment, or paste a URL to download.","Only needed when the document is password-protected.": "Only needed when the document is password-protected.",+ "Type placeholders in your Word template with double braces:\n- `{{name}}` is replaced by the \"name\" value. `{{customer.city}}` reads a nested value.\n- `{{#items}}` ... `{{/items}}` repeats a table row or paragraph for each entry of the \"items\" list. Inside it, use the entry's fields, like `{{description}}`.\n- `{{#paid}}` ... `{{/paid}}` shows the text only when \"paid\" is true; `{{^paid}}` ... `{{/paid}}` only when it is false or empty.": "Type placeholders in your Word template with double braces:\n- `{{name}}` is replaced by the \"name\" value. `{{customer.city}}` reads a nested value.\n- `{{#items}}` ... `{{/items}}` repeats a table row or paragraph for each entry of the \"items\" list. Inside it, use the entry's fields, like `{{description}}`.\n- `{{#paid}}` ... `{{/paid}}` shows the text only when \"paid\" is true; `{{^paid}}` ... `{{/paid}}` only when it is false or empty.",+ "A .docx file with {{placeholders}}, from an earlier step or a URL.": "A .docx file with {{placeholders}}, from an earlier step or a URL.",+ "One field per placeholder in the template. They appear once the template is set, or mapped from a step you have tested.": "One field per placeholder in the template. They appear once the template is set, or mapped from a step you have tested.",+ "Optional. A JSON object with values for the placeholders. It overrides the fields above, and is needed for a list inside a list.": "Optional. A JSON object with values for the placeholders. It overrides the fields above, and is needed for a list inside a list.",+ "Name of the new document. Leave empty to use the template's name.": "Name of the new document. Leave empty to use the template's name.","Document": "Document","Word Documents": "Word Documents"}\ No newline at end of filediff --git a/packages/pieces/core/word-documents/src/index.ts b/packages/pieces/core/word-documents/src/index.tsindex 8b5f29b2e0e..ad854c5da44 100644--- a/packages/pieces/core/word-documents/src/index.ts+++ b/packages/pieces/core/word-documents/src/index.ts@@ -1,14 +1,20 @@-import { createPiece, PieceAuth, PieceCategory } from '@activepieces/pieces-framework';+import {+ createPiece,+ PieceAuth,+ PieceCategory,+} from '@activepieces/pieces-framework';import { extractText } from './lib/actions/extract-text';+import { fillTemplate } from './lib/actions/fill-template';export const wordDocuments = createPiece({displayName: 'Word Documents',- description: 'Read Word documents (.docx) in your flow, no Microsoft account needed.',+ description:+ 'Read Word documents (.docx) and fill Word templates in your flow, no Microsoft account needed.',auth: PieceAuth.None(),minimumSupportedRelease: '0.88.2',logoUrl: 'https://cdn.activepieces.com/pieces/new-core/word-documents.svg',categories: [PieceCategory.CORE],authors: ['kishanprmr'],- actions: [extractText],+ actions: [extractText, fillTemplate],triggers: [],});diff --git a/packages/pieces/core/word-documents/src/lib/actions/extract-text.ts b/packages/pieces/core/word-documents/src/lib/actions/extract-text.tsindex 2e3db20f93a..662998fef07 100644--- a/packages/pieces/core/word-documents/src/lib/actions/extract-text.ts+++ b/packages/pieces/core/word-documents/src/lib/actions/extract-text.ts@@ -1,5 +1,11 @@-import { PieceAuth, Property, createAction, tryCatch } from '@activepieces/pieces-framework';+import {+ PieceAuth,+ Property,+ createAction,+ tryCatch,+} from '@activepieces/pieces-framework';import { OfficeContentNode, OfficeErrorType, OfficeParser } from 'officeparser';+import { wordFile } from '../common/word-file';import { extractTextActionOutputSchema } from '../output-schemas';export const extractText = createAction({@@ -9,15 +15,26 @@ export const extractText = createAction({classification: 'READ',displayName: 'Extract Text',description: 'Get the text, headers and footers of a Word document (.docx).',- aiMetadata: { description: 'Reads a Word document (.docx, .docm, .dotx, including password-protected ones) and returns its text in reading order: paragraphs, tables as aligned rows, lists, text boxes and footnotes, with page headers and footers returned separately. Use it to read a Word attachment or file before summarizing, classifying or parsing it; use Extract Text in the PDF piece for PDFs and Read File in Files Helper for plain-text files. Legacy .doc files are rejected with a request to save them as .docx; read-only and idempotent.', idempotent: true },+ aiMetadata: {+ description:+ 'Reads a Word document (.docx, .docm, .dotx, including password-protected ones) and returns its text in reading order: paragraphs, tables as aligned rows, lists, text boxes and footnotes, with page headers and footers returned separately. Use it to read a Word attachment or file before summarizing, classifying or parsing it; use Extract Text in the PDF piece for PDFs and Read File in Files Helper for plain-text files. Legacy .doc files are rejected with a request to save them as .docx; read-only and idempotent.',+ idempotent: true,+ },outputSchema: extractTextActionOutputSchema,propertyGroups: [- { key: 'input', display: 'section', label: 'Document', icon: 'paperclip', props: ['file', 'password'] },+ {+ key: 'input',+ display: 'section',+ label: 'Document',+ icon: 'paperclip',+ props: ['file', 'password'],+ },],props: {file: Property.File({displayName: 'Word Document',- description: 'Pick a .docx file from an earlier step, such as an email attachment, or paste a URL to download.',+ description:+ 'Pick a .docx file from an earlier step, such as an email attachment, or paste a URL to download.',required: true,}),password: Property.ShortText({@@ -28,11 +45,14 @@ export const extractText = createAction({},async run(context) {const { file, password } = context.propsValue;- if (isLegacyWordFile(file.data)) {- throw new Error('This is an older Word file (.doc), which is not supported yet. Open it in Word, save it as .docx, and try again.');+ if (wordFile.isLegacyDoc(file.data)) {+ throw new Error(wordFile.legacyDocMessage);}const { data: document, error } = await tryCatch(() =>- OfficeParser.parseOffice(file.data, { fileType: 'docx', password: password || undefined }),+ OfficeParser.parseOffice(file.data, {+ fileType: 'docx',+ password: password || undefined,+ }));if (error) {throw new Error(describeParseError(error));@@ -46,12 +66,10 @@ export const extractText = createAction({},});-function isLegacyWordFile(data: Buffer): boolean {- return data.subarray(0, CFB_SIGNATURE.length).equals(CFB_SIGNATURE) && !data.includes(ENCRYPTED_OOXML_STREAM_NAME);-}-function joinUniqueText(nodes: OfficeContentNode[] | undefined): string {- const texts = (nodes ?? []).map((node) => (node.text ?? '').trim()).filter((text) => text.length > 0);+ const texts = (nodes ?? [])+ .map((node) => (node.text ?? '').trim())+ .filter((text) => text.length > 0);return [...new Set(texts)].join('\n');}@@ -71,11 +89,13 @@ function getOfficeErrorCode(error: Error): string | undefined {return undefined;}const issue = error.officeIssue;- if (typeof issue !== 'object' || issue === null || !('code' in issue) || typeof issue.code !== 'string') {+ if (+ typeof issue !== 'object' ||+ issue === null ||+ !('code' in issue) ||+ typeof issue.code !== 'string'+ ) {return undefined;}return issue.code;}--const CFB_SIGNATURE = Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]);-const ENCRYPTED_OOXML_STREAM_NAME = Buffer.from('EncryptionInfo', 'utf16le');diff --git a/packages/pieces/core/word-documents/src/lib/actions/fill-template.ts b/packages/pieces/core/word-documents/src/lib/actions/fill-template.tsnew file mode 100644index 00000000000..aa8e22a3781--- /dev/null+++ b/packages/pieces/core/word-documents/src/lib/actions/fill-template.ts@@ -0,0 +1,470 @@+import { HttpError, HttpMethod, httpClient } from '@activepieces/pieces-common';+import {+ ApFile,+ DynamicPropsValue,+ MarkdownVariant,+ PieceAuth,+ Property,+ createAction,+ tryCatch,+} from '@activepieces/pieces-framework';+import Docxtemplater, { DXT } from 'docxtemplater';+import InspectModule from 'docxtemplater/js/inspect-module';+import PizZip from 'pizzip';+import { wordFile } from '../common/word-file';+import { fillTemplateActionOutputSchema } from '../output-schemas';++export const fillTemplate = createAction({+ auth: PieceAuth.None(),+ audience: 'both',+ name: 'fill_template',+ classification: 'READ',+ displayName: 'Fill Template',+ description:+ 'Fill the {{placeholders}} in a Word template (.docx) and get a new document.',+ aiMetadata: {+ description:+ 'Creates a new Word document (.docx) from a template by replacing its {{placeholders}} with values, keeping all formatting. Pass every value in data as one JSON object: nested values ({{customer.city}}), a list of objects to repeat a table row or paragraph per item ({{#items}}...{{/items}}), and true/false to show a section ({{#paid}}...{{/paid}}) or its opposite ({{^paid}}...{{/paid}}); fields only mirrors the template for the flow builder. Missing values come out blank. Use it to generate contracts, invoices, letters or certificates and pass the returned file to an email, storage or PDF step. The template itself is not changed, and the same inputs give the same document.',+ idempotent: true,+ },+ outputSchema: fillTemplateActionOutputSchema,+ props: {+ syntax: Property.MarkDown({+ value: `Type placeholders in your Word template with double braces:+- \`{{name}}\` is replaced by the "name" value. \`{{customer.city}}\` reads a nested value.+- \`{{#items}}\` ... \`{{/items}}\` repeats a table row or paragraph for each entry of the "items" list. Inside it, use the entry's fields, like \`{{description}}\`.+- \`{{#paid}}\` ... \`{{/paid}}\` shows the text only when "paid" is true; \`{{^paid}}\` ... \`{{/paid}}\` only when it is false or empty.`,+ variant: MarkdownVariant.INFO,+ }),+ template: Property.File({+ displayName: 'Word Template',+ description:+ 'A .docx file with {{placeholders}}, from an earlier step or a URL.',+ required: true,+ }),+ fields: Property.DynamicProperties({+ auth: PieceAuth.None(),+ displayName: 'Fields',+ description:+ 'One field per placeholder in the template. They appear once the template is set, or mapped from a step you have tested.',+ required: false,+ refreshers: ['template'],+ props: async ({ template }) => templateFields(template),+ }),+ data: Property.Json({+ displayName: 'Data (JSON)',+ description:+ 'Optional. A JSON object with values for the placeholders. It overrides the fields above, and is needed for a list inside a list.',+ required: false,+ }),+ fileName: Property.ShortText({+ displayName: 'File Name',+ description:+ "Name of the new document. Leave empty to use the template's name.",+ placeholder: 'contract.docx',+ required: false,+ }),+ },+ async run(context) {+ const { template, fields, data, fileName } = context.propsValue;+ const problem = findTemplateProblem(template.data);+ if (problem) {+ throw new Error(problem);+ }+ if (+ data !== undefined &&+ (typeof data !== 'object' || data === null || Array.isArray(data))+ ) {+ throw new Error(+ 'Data must be a JSON object, for example {"name": "Ada Lovelace"}.'+ );+ }+ const values = mergeValues({ fields: fields ?? {}, data: data ?? {} });+ const { data: rendered, error } = await tryCatch(async () =>+ renderTemplate({ template: template.data, data: values })+ );+ if (error) {+ throw new Error(describeTemplateError(error));+ }+ const name = toFileName({+ requested: fileName?.trim() || template.filename,+ extension: rendered.extension,+ });+ return {+ file: await context.files.write({+ fileName: name,+ data: rendered.document,+ }),+ fileName: name,+ };+ },+});++function renderTemplate({+ template,+ data,+}: {+ template: Buffer;+ data: Record<string, unknown>;+}): RenderedDocument {+ const zip = new PizZip(template);+ const document = createTemplater({ zip, modules: [] });+ document.render(data);+ const contentTypes = zip.file(CONTENT_TYPES_PART)?.asText() ?? '';+ zip.file(+ CONTENT_TYPES_PART,+ contentTypes+ .replace(+ 'wordprocessingml.template.main+xml',+ 'wordprocessingml.document.main+xml'+ )+ .replace(+ 'ms-word.template.macroEnabledTemplate.main+xml',+ 'ms-word.document.macroEnabled.main+xml'+ )+ );+ return {+ document: zip.generate({ type: 'nodebuffer', compression: 'DEFLATE' }),+ extension: contentTypes.includes('macroEnabled') ? 'docm' : 'docx',+ };+}++async function templateFields(template: unknown): Promise<DynamicPropsValue> {+ const { data: document, error: loadError } = await tryCatch(async () =>+ loadTemplate(template)+ );+ if (loadError) {+ return fieldsNotice(+ loadError instanceof MissingTemplateError+ ? 'Set the Word Template above, or map it from a step you have tested, to see its fields here. You can also fill the template with Data (JSON).'+ : `The template could not be downloaded (${describeDownloadError(+ loadError+ )}). Check the URL, or map the file from a step you have tested.`+ );+ }+ const problem = findTemplateProblem(document);+ if (problem) {+ return fieldsNotice(problem);+ }+ const { data: tags, error } = await tryCatch(async () =>+ listTemplateTags(document)+ );+ if (error) {+ return fieldsNotice(describeTemplateError(error));+ }+ if (tags.length === 0) {+ return fieldsNotice('This template has no {{placeholders}} yet.');+ }+ if (tags.length > MAX_FIELDS) {+ return fieldsNotice(+ `This template has ${tags.length} placeholders, too many to show as fields. Fill it with Data (JSON) instead.`+ );+ }+ return Object.fromEntries(+ tags.map((tag) => [tag.name, toFieldProperty(tag)])+ );+}++function describeDownloadError(error: Error): string {+ if (error instanceof HttpError) {+ return `the server answered ${error.response.status}`;+ }+ return error.message.slice(0, 200);+}++function fieldsNotice(message: string): DynamicPropsValue {+ return {+ fieldsNotice: Property.MarkDown({+ value: message,+ variant: MarkdownVariant.WARNING,+ }),+ };+}++function findTemplateProblem(template: Buffer): string | undefined {+ if (wordFile.isEncryptedDocx(template)) {+ return 'This template is password-protected. Remove the password in Word, save it, and try again.';+ }+ if (wordFile.isLegacyDoc(template)) {+ return wordFile.legacyDocMessage;+ }+ if (wordFile.exceedsUnzippedLimits(template)) {+ return 'This template is too large to fill. Templates up to about 1,500 pages of text and 200 MB in total are supported.';+ }+ return undefined;+}++function listTemplateTags(template: Buffer): TemplateTag[] {+ const inspector = new InspectModule();+ createTemplater({ zip: new PizZip(template), modules: [inspector] });+ const tags = inspector+ .getAllStructuredTags()+ .filter(isPlaceholder)+ .flatMap(toTemplateTags);+ const byName = new Map<string, TemplateTag>();+ tags.forEach((tag) => {+ const current = byName.get(tag.name);+ if (current?.kind === 'list' && tag.kind === 'list') {+ byName.set(tag.name, {+ ...current,+ fields: [...new Set([...current.fields, ...tag.fields])],+ });+ } else if (+ !current ||+ TAG_PRIORITY[tag.kind] > TAG_PRIORITY[current.kind]+ ) {+ byName.set(tag.name, tag);+ }+ });+ return [...byName.values()];+}++function toTemplateTags(part: DXT.Part): TemplateTag[] {+ const name = part.value.trim();+ if (UNFILLABLE_NAMES.has(name)) {+ return [];+ }+ if (part.module !== 'loop') {+ return [{ name, kind: 'text', fields: [] }];+ }+ const inner = (part.subparsed ?? [])+ .filter((child) => isPlaceholder(child) && child.module !== 'loop')+ .map((child) => child.value.trim());+ const fields = [+ ...new Set(+ inner.filter((field) => !UNFILLABLE_NAMES.has(field) && field !== name)+ ),+ ];+ if (part.inverted) {+ return [+ { name, kind: 'condition', fields: [] },+ ...fields.map(+ (field): TemplateTag => ({ name: field, kind: 'text', fields: [] })+ ),+ ];+ }+ if (fields.length > 0) {+ return [{ name, kind: 'list', fields }];+ }+ if (inner.includes('.')) {+ return [{ name, kind: 'textList', fields: [] }];+ }+ return [+ { name, kind: inner.includes(name) ? 'text' : 'condition', fields: [] },+ ];+}++function isPlaceholder(part: DXT.Part): boolean {+ return part.type === 'placeholder';+}++function toFieldProperty(tag: TemplateTag): DynamicPropsValue[string] {+ if (tag.kind === 'condition') {+ return Property.Checkbox({+ displayName: tag.name,+ description: `Shows or hides the {{#${tag.name}}} section.`,+ required: false,+ });+ }+ if (tag.kind === 'textList') {+ return Property.Array({+ displayName: tag.name,+ description: `One entry per item for the {{#${tag.name}}} section.`,+ required: false,+ });+ }+ if (tag.kind === 'list') {+ return Property.Array({+ displayName: tag.name,+ description: `One row per item for the {{#${tag.name}}} section.`,+ required: false,+ properties: Object.fromEntries(+ tag.fields.map((field) => [+ field,+ Property.ShortText({ displayName: field, required: false }),+ ])+ ),+ });+ }+ return Property.ShortText({ displayName: tag.name, required: false });+}++async function loadTemplate(value: unknown): Promise<Buffer> {+ if (value instanceof ApFile) {+ return value.data;+ }+ if (typeof value !== 'string' || value.trim().length === 0) {+ throw new MissingTemplateError();+ }+ const base64 = /^data:[^;]+;base64,(.+)$/.exec(value);+ if (base64) {+ return Buffer.from(base64[1], 'base64');+ }+ const response = await httpClient.sendRequest<ArrayBuffer>({+ method: HttpMethod.GET,+ url: value,+ responseType: 'arraybuffer',+ });+ return Buffer.from(response.body);+}++function mergeValues({+ fields,+ data,+}: {+ fields: Record<string, unknown>;+ data: Record<string, unknown>;+}): Record<string, unknown> {+ return Object.entries(fields)+ .filter(+ ([, value]) => value !== undefined && value !== null && value !== ''+ )+ .filter(([key]) => resolvePath({ scope: data, path: key }) === undefined)+ .reduce<Record<string, unknown>>(+ (merged, [key, value]) => ({ ...merged, [key]: value }),+ data+ );+}++function createTemplater({+ zip,+ modules,+}: {+ zip: PizZip;+ modules: DXT.Module[];+}): Docxtemplater<PizZip> {+ return new Docxtemplater(zip, {+ modules,+ delimiters: { start: '{{', end: '}}' },+ paragraphLoop: true,+ linebreaks: true,+ stripInvalidXMLChars: true,+ errorLogging: false,+ syntax: { allowUnopenedTag: true, allowUnclosedTag: true },+ nullGetter: () => '',+ parser: (tag) => {+ const path = tag.trim();+ return {+ get: (scope, context) => {+ const value = resolvePath({ scope, path });+ return context.meta.part.module === 'loop' ? value : toText(value);+ },+ };+ },+ });+}++function resolvePath({+ scope,+ path,+}: {+ scope: unknown;+ path: string;+}): unknown {+ if (path === '.') {+ return scope;+ }+ return (+ readOwn({ value: scope, key: path }) ??+ path+ .split('.')+ .reduce<unknown>((value, key) => readOwn({ value, key }), scope)+ );+}++function readOwn({ value, key }: { value: unknown; key: string }): unknown {+ return typeof value === 'object' &&+ value !== null &&+ Object.hasOwn(value, key)+ ? Reflect.get(value, key)+ : undefined;+}++function toText(value: unknown): unknown {+ return typeof value === 'object' && value !== null+ ? JSON.stringify(value)+ : value;+}++function toFileName({+ requested,+ extension,+}: {+ requested: string;+ extension: string;+}): string {+ return `${requested.replace(/\.(docx|docm|dotx|dotm)$/i, '')}.${extension}`;+}++function describeTemplateError(error: Error): string {+ const explanations = getTemplateErrorExplanations(error);+ if (+ explanations.length > 0 &&+ !hasErrorId({ error, id: 'filetype_not_identified' })+ ) {+ return `The template has a mistake in its placeholders: ${explanations.join(+ ' '+ )}`;+ }+ return `This file could not be read as a Word document (.docx). It may be damaged or in a different format. Details: ${error.message}`;+}++function hasErrorId({ error, id }: { error: unknown; id: string }): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ 'properties' in error &&+ typeof error.properties === 'object' &&+ error.properties !== null &&+ 'id' in error.properties &&+ error.properties.id === id+ );+}++function getTemplateErrorExplanations(error: unknown): string[] {+ if (typeof error !== 'object' || error === null || !('properties' in error)) {+ return [];+ }+ const { properties } = error;+ if (typeof properties !== 'object' || properties === null) {+ return [];+ }+ if ('errors' in properties && Array.isArray(properties.errors)) {+ return properties.errors.flatMap(getTemplateErrorExplanations);+ }+ if (+ 'explanation' in properties &&+ typeof properties.explanation === 'string'+ ) {+ return [properties.explanation];+ }+ return [];+}++const CONTENT_TYPES_PART = '[Content_Types].xml';++class MissingTemplateError extends Error {}++const MAX_FIELDS = 200;++const UNFILLABLE_NAMES = new Set(['', '.', '__proto__']);++const TAG_PRIORITY: Record<TemplateTagKind, number> = {+ list: 3,+ textList: 2,+ condition: 1,+ text: 0,+};++type TemplateTagKind = 'text' | 'list' | 'textList' | 'condition';++type TemplateTag = {+ name: string;+ kind: TemplateTagKind;+ fields: string[];+};++type RenderedDocument = {+ document: Buffer;+ extension: 'docx' | 'docm';+};diff --git a/packages/pieces/core/word-documents/src/lib/common/word-file.ts b/packages/pieces/core/word-documents/src/lib/common/word-file.tsnew file mode 100644index 00000000000..912fec73f8e--- /dev/null+++ b/packages/pieces/core/word-documents/src/lib/common/word-file.ts@@ -0,0 +1,149 @@+import { inflateRawSync } from 'node:zlib';++function isLegacyDoc(data: Buffer): boolean {+ return isCompoundFile(data) && !data.includes(ENCRYPTED_OOXML_STREAM_NAME);+}++function isEncryptedDocx(data: Buffer): boolean {+ return isCompoundFile(data) && data.includes(ENCRYPTED_OOXML_STREAM_NAME);+}++function isCompoundFile(data: Buffer): boolean {+ return data.subarray(0, CFB_SIGNATURE.length).equals(CFB_SIGNATURE);+}++function exceedsUnzippedLimits(data: Buffer): boolean {+ if (isZip64(data)) {+ return true;+ }+ const entries = listZipEntries(data);+ if (!entries) {+ return false;+ }+ const sizes = entries.reduce<{ xml: number; total: number } | undefined>(+ (totals, entry) => {+ if (!totals) {+ return undefined;+ }+ const isXml = XML_PART.test(entry.name);+ const budget = Math.min(+ MAX_UNZIPPED_BYTES - totals.total,+ isXml ? MAX_UNZIPPED_XML_BYTES - totals.xml : Infinity+ );+ const size = unzippedSize({ data, entry, budget });+ if (size === undefined) {+ return undefined;+ }+ return {+ xml: totals.xml + (isXml ? size : 0),+ total: totals.total + size,+ };+ },+ { xml: 0, total: 0 }+ );+ return (+ !sizes ||+ sizes.xml > MAX_UNZIPPED_XML_BYTES ||+ sizes.total > MAX_UNZIPPED_BYTES+ );+}++function isZip64(data: Buffer): boolean {+ const end = data.lastIndexOf(END_OF_CENTRAL_DIRECTORY);+ return (+ end >= 0 &&+ end + 22 <= data.length &&+ (data.readUInt16LE(end + 10) === ZIP64_COUNT_MARKER ||+ data.readUInt32LE(end + 16) === ZIP64_MARKER)+ );+}++function listZipEntries(data: Buffer): ZipEntry[] | undefined {+ const end = data.lastIndexOf(END_OF_CENTRAL_DIRECTORY);+ if (end < 0 || end + 22 > data.length) {+ return undefined;+ }+ const count = data.readUInt16LE(end + 10);+ const entries: ZipEntry[] = [];+ let offset = data.readUInt32LE(end + 16);+ for (let index = 0; index < count; index++) {+ if (+ offset + 46 > data.length ||+ data.readUInt32LE(offset) !== CENTRAL_DIRECTORY_ENTRY+ ) {+ return undefined;+ }+ const nameLength = data.readUInt16LE(offset + 28);+ entries.push({+ name: data.toString('utf8', offset + 46, offset + 46 + nameLength),+ method: data.readUInt16LE(offset + 10),+ compressedSize: data.readUInt32LE(offset + 20),+ localHeaderOffset: data.readUInt32LE(offset + 42),+ });+ offset +=+ 46 ++ nameLength ++ data.readUInt16LE(offset + 30) ++ data.readUInt16LE(offset + 32);+ }+ return entries;+}++function unzippedSize({+ data,+ entry,+ budget,+}: {+ data: Buffer;+ entry: ZipEntry;+ budget: number;+}): number | undefined {+ const header = entry.localHeaderOffset;+ if (entry.compressedSize === ZIP64_MARKER || header + 30 > data.length) {+ return undefined;+ }+ const start =+ header ++ 30 ++ data.readUInt16LE(header + 26) ++ data.readUInt16LE(header + 28);+ const compressed = data.subarray(start, start + entry.compressedSize);+ if (entry.method !== DEFLATE) {+ return compressed.length;+ }+ try {+ return inflateRawSync(compressed, {+ maxOutputLength: Math.max(budget, 0) + 1,+ }).length;+ } catch (error) {+ return error instanceof RangeError ? undefined : compressed.length;+ }+}++const CFB_SIGNATURE = Buffer.from([+ 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1,+]);+const ENCRYPTED_OOXML_STREAM_NAME = Buffer.from('EncryptionInfo', 'utf16le');+const END_OF_CENTRAL_DIRECTORY = Buffer.from([0x50, 0x4b, 0x05, 0x06]);+const CENTRAL_DIRECTORY_ENTRY = 0x02014b50;+const ZIP64_MARKER = 0xffffffff;+const ZIP64_COUNT_MARKER = 0xffff;+const DEFLATE = 8;+const XML_PART = /\.(xml|rels)$/i;+const MAX_UNZIPPED_XML_BYTES = 8 * 1024 * 1024;+const MAX_UNZIPPED_BYTES = 200 * 1024 * 1024;++export const wordFile = {+ isLegacyDoc,+ isEncryptedDocx,+ exceedsUnzippedLimits,+ legacyDocMessage:+ 'This is an older Word file (.doc), which is not supported yet. Open it in Word, save it as .docx, and try again.',+};++type ZipEntry = {+ name: string;+ method: number;+ compressedSize: number;+ localHeaderOffset: number;+};diff --git a/packages/pieces/core/word-documents/src/lib/output-schemas.ts b/packages/pieces/core/word-documents/src/lib/output-schemas.tsindex b9cca755d72..216159342f5 100644--- a/packages/pieces/core/word-documents/src/lib/output-schemas.ts+++ b/packages/pieces/core/word-documents/src/lib/output-schemas.ts@@ -2,8 +2,33 @@ import { OutputSchema } from '@activepieces/pieces-framework';export const extractTextActionOutputSchema: OutputSchema = {fields: [- { key: 'text', label: 'Text', description: 'Paragraphs, tables, lists, text boxes and footnotes in reading order.' },- { key: 'headers', label: 'Headers', description: 'Text of the page headers, one per line.' },- { key: 'footers', label: 'Footers', description: 'Text of the page footers, one per line.' },+ {+ key: 'text',+ label: 'Text',+ description:+ 'Paragraphs, tables, lists, text boxes and footnotes in reading order.',+ },+ {+ key: 'headers',+ label: 'Headers',+ description: 'Text of the page headers, one per line.',+ },+ {+ key: 'footers',+ label: 'Footers',+ description: 'Text of the page footers, one per line.',+ },+ ],+};++export const fillTemplateActionOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'file',+ label: 'File',+ description:+ 'The filled document, ready to attach to an email or upload.',+ },+ { key: 'fileName', label: 'File Name' },],};diff --git a/packages/pieces/core/word-documents/test/data/template-data.json b/packages/pieces/core/word-documents/test/data/template-data.jsonnew file mode 100644index 00000000000..04999fae8ea--- /dev/null+++ b/packages/pieces/core/word-documents/test/data/template-data.json@@ -0,0 +1,53 @@+{+ "first_name": "Ada",+ "last_name": "Lovelace",+ "zero": 0,+ "flag_false": false,+ "nil": null,+ "special": "Tom & Jerry <b> \"q\" 'a' 😀 مرحبا",+ "address": "Line1\nLine2",+ "customer": {+ "city": "Paris"+ },+ "First Name": "SpaceAda",+ "customer-id": "C-42",+ "company": "Acme",+ "paid": true,+ "unpaid": false,+ "items": [+ {+ "name": "Widget",+ "qty": 2+ },+ {+ "name": "Gadget",+ "qty": 5+ }+ ],+ "none": [],+ "orders": [+ {+ "id": "O1",+ "lines": [+ {+ "sku": "S1"+ },+ {+ "sku": "S2"+ }+ ]+ },+ {+ "id": "O2",+ "lines": [+ {+ "sku": "S3"+ }+ ]+ }+ ],+ "tags": [+ "red",+ "blue"+ ]+}diff --git a/packages/pieces/core/word-documents/test/data/template.docx b/packages/pieces/core/word-documents/test/data/template.docxnew file mode 100644index 00000000000..3e9ff51b8e6Binary files /dev/null and b/packages/pieces/core/word-documents/test/data/template.docx differdiff --git a/packages/pieces/core/word-documents/test/extract-text.test.ts b/packages/pieces/core/word-documents/test/extract-text.test.tsindex f8dd3fae269..949af052091 100644--- a/packages/pieces/core/word-documents/test/extract-text.test.ts+++ b/packages/pieces/core/word-documents/test/extract-text.test.ts@@ -3,11 +3,18 @@import { readFileSync } from 'fs';import { join } from 'path';import { extractText } from '../src/lib/actions/extract-text';-import { createMockActionContext, ApFile } from '@activepieces/pieces-framework';+import {+ createMockActionContext,+ ApFile,+} from '@activepieces/pieces-framework';function runWithFile({ data, password }: { data: Buffer; password?: string }) {const file = new ApFile('document.docx', data, 'docx');- return extractText.run(createMockActionContext<typeof extractText.props>({ propsValue: { file, password } }));+ return extractText.run(+ createMockActionContext<typeof extractText.props>({+ propsValue: { file, password },+ })+ );}function fixture(name: string): Buffer {@@ -17,7 +24,10 @@ function fixture(name: string): Buffer {describe('extractText', () => {test('returns body, tables, footnotes, headers and footers', async () => {const result = await runWithFile({ data: fixture('sample.docx') });- expect(result).toMatchObject({ headers: 'HEADER_TEXT', footers: 'FOOTER_TEXT' });+ expect(result).toMatchObject({+ headers: 'HEADER_TEXT',+ footers: 'FOOTER_TEXT',+ });for (const expected of ['Body with footnote','LINK_TEXT',@@ -31,30 +41,48 @@ describe('extractText', () => {});test('opens a password-protected document with its password', async () => {- const result = await runWithFile({ data: fixture('password-protected.docx'), password: 'secret' });- expect(result).toMatchObject({ text: expect.stringContaining('Body with footnote'), headers: 'HEADER_TEXT' });+ const result = await runWithFile({+ data: fixture('password-protected.docx'),+ password: 'secret',+ });+ expect(result).toMatchObject({+ text: expect.stringContaining('Body with footnote'),+ headers: 'HEADER_TEXT',+ });});test('asks for the password when it is missing', async () => {- await expect(runWithFile({ data: fixture('password-protected.docx') })).rejects.toThrow(- 'This document is password-protected. Enter its password in the Password field.',+ await expect(+ runWithFile({ data: fixture('password-protected.docx') })+ ).rejects.toThrow(+ 'This document is password-protected. Enter its password in the Password field.');});test('reports a wrong password', async () => {- await expect(runWithFile({ data: fixture('password-protected.docx'), password: 'wrong' })).rejects.toThrow(- 'The password is incorrect for this document.',- );+ await expect(+ runWithFile({+ data: fixture('password-protected.docx'),+ password: 'wrong',+ })+ ).rejects.toThrow('The password is incorrect for this document.');});test('rejects legacy .doc files with a save-as hint', async () => {- const legacyDoc = Buffer.concat([Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]), Buffer.alloc(504)]);- await expect(runWithFile({ data: legacyDoc })).rejects.toThrow('save it as .docx');+ const legacyDoc = Buffer.concat([+ Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]),+ Buffer.alloc(504),+ ]);+ await expect(runWithFile({ data: legacyDoc })).rejects.toThrow(+ 'save it as .docx'+ );});test('rejects files that are not Word documents', async () => {- await expect(runWithFile({ data: Buffer.from('plain text, not a document') })).rejects.toThrow(- 'This file could not be read as a Word document (.docx).',+ await expect(+ runWithFile({ data: Buffer.from('plain text, not a document') })+ ).rejects.toThrow(+ 'This file could not be read as a Word document (.docx).');});});diff --git a/packages/pieces/core/word-documents/test/fill-template.test.ts b/packages/pieces/core/word-documents/test/fill-template.test.tsnew file mode 100644index 00000000000..94445c4e0b4--- /dev/null+++ b/packages/pieces/core/word-documents/test/fill-template.test.ts@@ -0,0 +1,356 @@+/// <reference types="vitest/globals" />++import { readFileSync } from 'fs';+import { join } from 'path';+import PizZip from 'pizzip';+import { OfficeParser } from 'officeparser';+import { fillTemplate } from '../src/lib/actions/fill-template';+import {+ createMockActionContext,+ ApFile,+} from '@activepieces/pieces-framework';++async function runFill({+ template,+ data,+ fields,+ fileName,+ templateName = 'template.docx',+}: RunFillParams) {+ const written: { fileName: string; data: Buffer }[] = [];+ const context = createMockActionContext<typeof fillTemplate.props>({+ propsValue: {+ template: new ApFile(templateName, template, 'docx'),+ data,+ fields,+ fileName,+ syntax: undefined,+ },+ });+ const result = await fillTemplate.run({+ ...context,+ files: {+ ...context.files,+ write: async ({ fileName: name, data: content }) => {+ if (!Buffer.isBuffer(content)) {+ throw new Error('Expected the document as a Buffer');+ }+ written.push({ fileName: name, data: content });+ return 'file-url';+ },+ },+ });+ return { result, document: written[0].data };+}++function propertyContext() {+ return createMockActionContext<typeof fillTemplate.props>({+ propsValue: {+ template: new ApFile('template.docx', Buffer.alloc(0), 'docx'),+ fields: undefined,+ data: undefined,+ fileName: undefined,+ syntax: undefined,+ },+ });+}++async function listFields(template: Buffer) {+ const context = propertyContext();+ const props = await fillTemplate.props.fields.props(+ { template: new ApFile('template.docx', template, 'docx') },+ context+ );+ return Object.fromEntries(+ Object.entries(props).map(([key, property]) => [+ key,+ 'properties' in property && property.properties+ ? `${property.type}[${Object.keys(property.properties).join(',')}]`+ : property.type,+ ])+ );+}++async function fieldsNotice(template: unknown): Promise<string> {+ const context = propertyContext();+ const props = await fillTemplate.props.fields.props({ template }, context);+ const notice = props['fieldsNotice'];+ return notice && 'description' in notice ? String(notice.description) : '';+}++function addParagraphs(paragraphs: string[]): Buffer {+ return editTemplate({+ part: 'word/document.xml',+ edit: (xml) =>+ xml.replace(+ '<w:body>',+ `<w:body>${paragraphs+ .map(+ (text) =>+ `<w:p><w:r><w:t xml:space="preserve">${text}</w:t></w:r></w:p>`+ )+ .join('')}`+ ),+ });+}++async function readText(document: Buffer): Promise<string> {+ const ast = await OfficeParser.parseOffice(document, { fileType: 'docx' });+ const { value } = await ast.to('text', { includeImages: false });+ return (+ [...(ast.auxiliary?.headers ?? []), ...(ast.auxiliary?.footers ?? [])]+ .map((node) => node.text)+ .join('\n') ++ '\n' ++ value+ );+}++function fixture(name: string): Buffer {+ return readFileSync(join(__dirname, 'data', name));+}++function editTemplate({+ part,+ edit,+}: {+ part: string;+ edit: (xml: string) => string;+}): Buffer {+ const zip = new PizZip(fixture('template.docx'));+ zip.file(part, edit(zip.file(part)?.asText() ?? ''));+ return zip.generate({ type: 'nodebuffer', compression: 'DEFLATE' });+}++const data = JSON.parse(+ readFileSync(join(__dirname, 'data', 'template-data.json'), 'utf8')+);++describe('fillTemplate', () => {+ test('fills placeholders, loops, conditions, headers, footers and footnotes', async () => {+ const { result, document } = await runFill({+ template: fixture('template.docx'),+ data,+ });+ expect(result).toEqual({ file: 'file-url', fileName: 'template.docx' });+ const text = await readText(document);+ for (const expected of [+ 'HEADER:Acme',+ 'FOOTER:Acme',+ 'SPLIT:Ada',+ 'MISSING:[]',+ 'ZERO:0 FALSE:false NULL:[]',+ `SPECIAL:Tom & Jerry <b> "q" 'a' 😀 مرحبا`,+ 'NESTED:Paris',+ 'SPACEKEY:SpaceAda',+ 'PROTO:[]',+ 'LITERAL:{"json": {"a": 1}} and {single}',+ 'ELSE_RIGHT',+ 'red;blue;',+ 'TEXTBOX:Acme',+ 'SDT:Acme',+ /Widget\s*\|\s*2/,+ /Gadget\s*\|\s*5/,+ /ORDER:O2\s+LINE:S3/,+ ]) {+ expect(text).toMatch(expected);+ }+ for (const unexpected of [+ 'IF_FALSE_SHOULD_HIDE',+ 'EMPTY_ROW_SHOULD_VANISH',+ 'ELSE_WRONG',+ ]) {+ expect(text).not.toContain(unexpected);+ }+ expect(new PizZip(document).file('word/footnotes.xml')?.asText()).toContain(+ 'FOOTNOTE:Acme'+ );+ });++ test('prints objects as JSON instead of [object Object]', async () => {+ const { document } = await runFill({+ template: fixture('template.docx'),+ data: { ...data, company: { name: 'Acme' } },+ });+ expect(await readText(document)).toContain('TEXTBOX:{"name":"Acme"}');+ });++ test('turns a .dotx template into a .docx document', async () => {+ const template = editTemplate({+ part: '[Content_Types].xml',+ edit: (xml) =>+ xml.replace(+ 'wordprocessingml.document.main+xml',+ 'wordprocessingml.template.main+xml'+ ),+ });+ const { result, document } = await runFill({+ template,+ data,+ templateName: 'letter.dotx',+ fileName: 'Contract',+ });+ expect(result).toMatchObject({ fileName: 'Contract.docx' });+ expect(+ new PizZip(document).file('[Content_Types].xml')?.asText()+ ).toContain('wordprocessingml.document.main+xml');+ });++ test('keeps macro-enabled templates as .docm', async () => {+ const template = editTemplate({+ part: '[Content_Types].xml',+ edit: (xml) =>+ xml.replace(+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml',+ 'application/vnd.ms-word.template.macroEnabledTemplate.main+xml'+ ),+ });+ const { result, document } = await runFill({+ template,+ data,+ templateName: 'letter.dotm',+ fileName: 'letter.docx',+ });+ expect(result).toMatchObject({ fileName: 'letter.docm' });+ expect(+ new PizZip(document).file('[Content_Types].xml')?.asText()+ ).toContain('ms-word.document.macroEnabled.main+xml');+ });++ test('explains a broken loop in the template', async () => {+ const template = editTemplate({+ part: 'word/document.xml',+ edit: (xml) => xml.replace('{{/items}}', ''),+ });+ await expect(runFill({ template, data })).rejects.toThrow(+ 'The template has a mistake in its placeholders: The loop with tag "items" is unclosed'+ );+ });++ test('lists a field for each placeholder in the template', async () => {+ expect(await listFields(fixture('template.docx'))).toMatchObject({+ company: 'SHORT_TEXT',+ 'customer.city': 'SHORT_TEXT',+ 'First Name': 'SHORT_TEXT',+ paid: 'CHECKBOX',+ unpaid: 'CHECKBOX',+ items: 'ARRAY[name,qty]',+ tags: 'ARRAY',+ orders: 'ARRAY[id]',+ });+ });++ test('keeps list rows when a list has an empty-list fallback, and merges list columns', async () => {+ const fields = await listFields(+ addParagraphs([+ '{{#items}}{{sku}}{{/items}}{{^items}}No items{{/items}}',+ '{{#paid}}PAID{{/paid}}{{^paid}}Due by {{due_date}}{{/paid}}',+ '{{__proto__}}',+ ])+ );+ expect(fields).toMatchObject({+ items: 'ARRAY[sku,name,qty]',+ paid: 'CHECKBOX',+ due_date: 'SHORT_TEXT',+ });+ expect(Object.hasOwn(fields, '__proto__')).toBe(false);+ });++ test('explains why fields are missing', async () => {+ expect(await fieldsNotice(undefined)).toContain(+ 'Set the Word Template above'+ );+ expect(+ await fieldsNotice(+ new ApFile('t.docx', fixture('password-protected.docx'), 'docx')+ )+ ).toContain('password-protected');+ const broken = editTemplate({+ part: 'word/document.xml',+ edit: (xml) => xml.replace('{{/items}}', ''),+ });+ expect(await fieldsNotice(new ApFile('t.docx', broken, 'docx'))).toContain(+ 'The loop with tag "items" is unclosed'+ );+ const crowded = addParagraphs(+ Array.from({ length: 201 }, (_, index) => `{{field_${index}}}`)+ );+ expect(await fieldsNotice(new ApFile('t.docx', crowded, 'docx'))).toContain(+ 'too many to show as fields'+ );+ });++ test('fills from fields, and data overrides them without empty fields getting in the way', async () => {+ const { document } = await runFill({+ template: fixture('template.docx'),+ data: { first_name: 'FromJson', customer: { city: 'Rome' } },+ fields: {+ first_name: 'FromField',+ 'customer.city': 'FromField',+ company: 'FieldCo',+ items: [{ name: 'FieldRow', qty: '7' }],+ },+ });+ const text = await readText(document);+ expect(text).toContain('SPLIT:FromJson');+ expect(text).toContain('NESTED:Rome');+ expect(text).toContain('TEXTBOX:FieldCo');+ expect(text).toMatch(/FieldRow\s*\|\s*7/);+ });++ test('rejects templates that unzip to more than the size limit', async () => {+ const bomb = editTemplate({+ part: 'word/document.xml',+ edit: (xml) =>+ xml.replace(+ '<w:body>',+ `<w:body><!--${'0'.repeat(9 * 1024 * 1024)}-->`+ ),+ });+ expect(bomb.length).toBeLessThan(200 * 1024);+ await expect(runFill({ template: bomb, data })).rejects.toThrow(+ 'This template is too large to fill.'+ );+ });++ test('rejects data that is not a JSON object', async () => {+ await expect(+ runFill({+ template: fixture('template.docx'),+ data: JSON.parse('[{"name": "Ada"}]'),+ })+ ).rejects.toThrow('Data must be a JSON object');+ });++ test('rejects password-protected templates', async () => {+ await expect(+ runFill({ template: fixture('password-protected.docx'), data })+ ).rejects.toThrow('This template is password-protected.');+ });++ test('rejects legacy .doc templates with a save-as hint', async () => {+ const legacyDoc = Buffer.concat([+ Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]),+ Buffer.alloc(504),+ ]);+ await expect(runFill({ template: legacyDoc, data })).rejects.toThrow(+ 'save it as .docx'+ );+ });++ test('rejects files that are not Word documents', async () => {+ await expect(+ runFill({ template: Buffer.from('plain text, not a document'), data })+ ).rejects.toThrow(+ 'This file could not be read as a Word document (.docx).'+ );+ });+});++type RunFillParams = {+ template: Buffer;+ data: Record<string, unknown>;+ fields?: Record<string, unknown>;+ fileName?: string;+ templateName?: string;+};diff --git a/packages/pieces/core/word-documents/vitest.config.ts b/packages/pieces/core/word-documents/vitest.config.tsindex f520fc14113..39dd18c1109 100644--- a/packages/pieces/core/word-documents/vitest.config.ts+++ b/packages/pieces/core/word-documents/vitest.config.ts@@ -1,7 +1,7 @@-import path from 'path'-import { defineConfig } from 'vitest/config'+import path from 'path';+import { defineConfig } from 'vitest/config';-const repoRoot = path.resolve(__dirname, '../../../..')+const repoRoot = path.resolve(__dirname, '../../../..');export default defineConfig({test: {@@ -10,9 +10,18 @@ export default defineConfig({},resolve: {alias: {- '@activepieces/shared': path.resolve(repoRoot, 'packages/core/shared/src/index.ts'),- '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),- '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ '@activepieces/shared': path.resolve(+ repoRoot,+ 'packages/core/shared/src/index.ts'+ ),+ '@activepieces/pieces-framework': path.resolve(+ repoRoot,+ 'packages/pieces/framework/src/index.ts'+ ),+ '@activepieces/pieces-common': path.resolve(+ repoRoot,+ 'packages/pieces/common/src/index.ts'+ ),},},-})+});