/* Pactsprig core: turns a Common Paper agreement template (templates/.json) plus the user's Cover Page answers * into a document model used by the preview, the PDF writer and the DOCX writer. Pure functions, no DOM. * The Standard Terms are never altered: they are passed through exactly as stored in the template. * © 2026 CyberMax. All rights reserved. Agreement text: Common Paper, CC BY 4.0 (see LICENSES.md). */ (function (root) { "use strict"; var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var BLANK = "__________"; var DISCLAIMER = "Pactsprig fills in published standard agreements; it is not a law firm and does not give legal advice. Have a lawyer review important contracts."; var CREDIT = "Prepared with Pactsprig by CyberMax"; var LICENCE_URL = "https://creativecommons.org/licenses/by/4.0/"; function isoToday(d) { d = d || new Date(); return d.getFullYear() + "-" + ("0" + (d.getMonth() + 1)).slice(-2) + "-" + ("0" + d.getDate()).slice(-2); } /** "2026-10-02" -> "October 2, 2026" (US style, as the standards are US agreements). */ function fmtDate(iso) { var m = /^(\d{4})-(\d\d)-(\d\d)$/.exec(iso || ""); if (!m) return ""; return MONTHS[+m[2] - 1] + " " + (+m[3]) + ", " + m[1]; } function clean(s) { return String(s == null ? "" : s).replace(/\r\n?/g, "\n").trim(); } /* ---------- default answers ---------- */ function varDefault(spec, today) { if (!spec) return ""; if (spec.d === "@today") return today; return spec.d == null ? "" : String(spec.d); } function eachVar(o, key, fn) { Object.keys((o && o.in) || {}).forEach(function (v) { fn(key + "." + v, o.in[v], v); }); } /** Default Cover Page answers for a template: a flat map of keys -> string/boolean. */ function defaults(tpl, today) { today = today || isoToday(); var v = {}; (tpl.cover || []).forEach(function (pg) { (pg.rows || []).forEach(function (row) { if (!row.id) return; var k = pg.id + ":" + row.id; if (row.type === "text" || row.type === "textarea") v[k] = row.d || ""; else if (row.type === "line") eachVar(row, k, function (key, spec) { v[key] = varDefault(spec, today); }); else if (row.type === "choice" || row.type === "checks") { if (row.type === "choice") v[k] = row.d || ""; (row.options || []).forEach(function (o) { var ok = k + "." + o.id; if (row.type === "checks") v[ok] = !!(row.d && row.d[o.id]); eachVar(o, ok, function (key, spec) { v[key] = varDefault(spec, today); }); (o.sub || []).forEach(function (s) { var sk = ok + "." + s.id; v[sk] = false; eachVar(s, sk, function (key, spec) { v[key] = varDefault(spec, today); }); }); }); } }); }); return v; } function emptyParty() { return { company: "", name: "", title: "", address: "" }; } /* ---------- filling templates ---------- */ /** Fill "{var}" placeholders. Returns {t, missing}. Globals: {@p1} {@p2} {@eff}. */ function fill(t, key, spec, vals, ctx) { var missing = false; var out = String(t).replace(/\{(@?\w+)\}/g, function (m0, name, off, str) { var val; if (name.charAt(0) === "@") val = ctx.globals[name.slice(1)]; else { val = vals[key + "." + name]; var s = spec && spec[name]; if (s && s.k === "date") val = fmtDate(val); } val = clean(val); if (!val) { missing = true; return BLANK; } // "Example, Inc." followed by "." in the template: avoid a double full stop if (/\.$/.test(val) && str.charAt(off + m0.length) === ".") val = val.slice(0, -1); return val; }); return { t: out, missing: missing }; } function rowItems(pg, row, vals, ctx) { var k = pg.id + ":" + row.id, items = []; var lead = row.lead ? [{ t: row.lead, lvl: 0, lead: true }] : []; var base = row.lead ? 1 : 0; function push(f, lvl, bullet) { items.push({ t: f.t, lvl: lvl, bullet: !!bullet, missing: f.missing }); } if (row.type === "fixed") return { items: [{ t: row.t, lvl: 0 }] }; if (row.type === "text" || row.type === "textarea") { var val = clean(vals[k]); if (!val) { if (row.empty) return { items: [{ t: row.empty, lvl: 0 }] }; if (row.optional) return null; return { items: [{ t: BLANK, lvl: 0, missing: true }], missing: true }; } val.split(/\n+/).forEach(function (line, i) { items.push({ t: (i === 0 && row.prefix ? row.prefix : "") + line, lvl: 0 }); }); return { items: items }; } if (row.type === "line") { var f = fill(row.t, k, row.in, vals, ctx); push(f, 0); return { items: items, missing: f.missing }; } var anyMissing = false; function subs(o, ok, lvl) { (o.sub || []).forEach(function (s) { if (!vals[ok + "." + s.id]) return; var fs = fill(s.t, ok + "." + s.id, s.in, vals, ctx); anyMissing = anyMissing || fs.missing; push(fs, lvl, true); }); } if (row.type === "choice") { var sel = (row.options || []).filter(function (o) { return o.id === vals[k]; })[0]; if (!sel) { if (row.optional) return null; return { items: [{ t: BLANK, lvl: 0, missing: true }], missing: true }; } var fc = fill(sel.t, k + "." + sel.id, sel.in, vals, ctx); items = lead.slice(); push(fc, base); anyMissing = fc.missing; subs(sel, k + "." + sel.id, base + 1); return { items: items, missing: anyMissing }; } if (row.type === "checks") { items = lead.slice(); (row.options || []).forEach(function (o) { var ok = k + "." + o.id; if (!vals[ok]) return; var fo = fill(o.t, ok, o.in, vals, ctx); anyMissing = anyMissing || fo.missing; push(fo, base, true); subs(o, ok, base + 1); }); if (items.length === lead.length) return row.optional ? null : { items: lead.concat([{ t: "None.", lvl: base }]) }; return { items: items, missing: anyMissing }; } return null; } function partyLabel(tpl, i, p) { var role = (tpl.partyRoles || tpl.parties || ["Party 1", "Party 2"])[i]; return { role: role, company: clean(p && p.company) }; } /** * Build the document model. * state: { values, parties: [p1, p2], today } * Returns { title, pages: [{title, kicker, intro, lead, rows, closing, sign}], terms, attribution, termsUrl, licenceUrl, missing: [...] } */ function build(tpl, state) { state = state || {}; var vals = state.values || defaults(tpl, state.today); var parties = state.parties || [emptyParty(), emptyParty()]; var missing = []; var eff = vals["keyterms:effective"] === "date" ? fmtDate(vals["keyterms:effective.date.date"]) : (vals["keyterms:effective"] === "sig" ? "the date of last signature on the Key Terms Cover Page" : ""); var ctx = { globals: { p1: clean(parties[0] && parties[0].company), p2: clean(parties[1] && parties[1].company), eff: eff } }; [0, 1].forEach(function (i) { var p = parties[i] || {}, role = partyLabel(tpl, i, p).role; if (!clean(p.company)) missing.push(role + " company name"); if (!clean(p.name)) missing.push(role + " signer name"); }); var pages = (tpl.cover || []).map(function (pg) { var rows = [], byId = {}; (pg.rows || []).forEach(function (row) { if (row.type === "heading") { rows.push({ heading: row.label }); return; } var r = rowItems(pg, row, vals, ctx); if (!r) return; if (r.missing) missing.push(row.label || (byId[row.after] && byId[row.after].label) || row.id); if (row.after && byId[row.after]) { byId[row.after].items = byId[row.after].items.concat(r.items); return; } var label = row.omitLabel && row.after ? ((pg.rows.filter(function (x) { return x.id === row.after; })[0] || {}).label || row.label) : row.label; var out = { id: row.id, label: label, sub: row.sub || "", items: r.items }; byId[row.id] = out; rows.push(out); }); // drop headings with no rows under them rows = rows.filter(function (r, i) { return !r.heading || (rows[i + 1] && !rows[i + 1].heading); }); var cols = [0, 1].map(function (i) { var p = parties[i] || {}, pl = partyLabel(tpl, i, p); return { head: tpl.id === "mnda" ? pl.role.toUpperCase() : pl.role.toUpperCase() + ": " + (pl.company || "[official company name]"), party: p }; }); var sign = (pg.sign || []).map(function (label) { var key = { "Print Name": "name", "Title": "title", "Company": "company", "Notice Address": "address" }[label]; return { label: label, note: label === "Notice Address" ? "Use email or postal address" : "", line: !key, values: cols.map(function (c) { return key ? clean(c.party[key]) : ""; }) }; }); return { id: pg.id, title: pg.title, kicker: pg.kicker || "", intro: pg.intro || "", lead: pg.lead || "", rows: rows, closing: pg.closing || "", sign: { heads: cols.map(function (c) { return c.head; }), rows: sign } }; }); return { id: tpl.id, title: tpl.name, version: tpl.version, pages: pages, terms: tpl.terms || [], attribution: tpl.attribution, termsUrl: tpl.termsUrl, licenceUrl: tpl.licenceUrl || LICENCE_URL, termsTitle: "Standard Terms", termsNote: "Common Paper " + tpl.name + " Standard Terms Version " + tpl.version + ", posted at " + tpl.termsUrl.replace(/^https:\/\//, "") + ". Copy attached for convenience only.", missing: missing.filter(function (m, i, a) { return a.indexOf(m) === i; }), }; } /** Plain text of the Standard Terms in a template (for tests and checks). */ function termsText(tpl) { return (tpl.terms || []).map(function (b) { return [b.n, b.h, b.h3].filter(Boolean).join(" ") + "\n" + (b.r || []).map(function (x) { return typeof x === "string" ? x : x[1]; }).join(""); }).join("\n"); } /** File name such as "Mutual-NDA-Northwind-Analytics-Harbor-Pine-Robotics.pdf". */ function fileName(tpl, parties, ext) { var parts = [tpl.short || tpl.name].concat((parties || []).map(function (p) { return p && p.company; })).filter(Boolean).join("-"); return parts.normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/\b(Inc|LLC|Ltd|Corp|GmbH)\b\.?/gi, "").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "").slice(0, 90) + "." + (ext || "pdf"); } /** Example data used by "Load example" and the first screen. */ var EXAMPLES = { mnda: { parties: [ { company: "Northwind Analytics, Inc.", name: "Dana Reyes", title: "Chief Executive Officer", address: "legal@northwind-analytics.example" }, { company: "Harbor & Pine Robotics LLC", name: "Sam Okafor", title: "Chief Operating Officer", address: "200 Wharf Road, Wilmington, DE 19801" }, ], values: { "mnda:purpose": "Evaluating a possible data analytics partnership, including sharing product roadmaps, pricing and sample warehouse data.", "mnda:term.fixed.years": "1", "mnda:conf.fixed.years": "2", "mnda:law.state": "Delaware", "mnda:court.place": "New Castle County, Delaware", }, }, psa: { parties: [ { company: "Brightline Studio LLC", name: "Maya Chen", title: "Managing Partner", address: "hello@brightline.example" }, { company: "Cedar & Co. Dental Group, Inc.", name: "Luis Moreno", title: "Operations Director", address: "88 Elm Street, Austin, TX 78701" }, ], values: { "keyterms:law.state": "the State of Texas", "keyterms:court.place": "Travis County, Texas", "keyterms:cap.mult.x": "1", "keyterms:publicity": "private", "sow:sowref.num": "1", "sow:services": "Redesign and rebuild the Cedar & Co. website (12 pages) with online booking. Lead designer: Maya Chen. Timeline: discovery in week 1, designs by week 4, launch by week 10.", "sow:deliverables": "Website design files, the finished website code and content, and a 1-hour training session recording.", "sow:delivOpts.accept": true, "sow:delivOpts.accept.rej": true, "sow:delivOpts.accept.resub": true, "sow:fees": "Fixed fee of $18,000: 30% on signing, 40% on design approval, 30% on launch.", "sow:invoice.text": "At each milestone", "sow:obligations": "Name one point of contact, provide content and photos by week 3, and give feedback within 5 business days.", }, }, "design-partner": { parties: [ { company: "Lumen Ledger, Inc.", name: "Priya Shah", title: "Co-founder and CEO", address: "priya@lumenledger.example" }, { company: "Fieldstone Bakery Group LLC", name: "Tom Becker", title: "Finance Director", address: "tom@fieldstone.example" }, ], values: { "keyterms:product.text": "Lumen Ledger, a bookkeeping app that matches bank transactions to receipts automatically", "keyterms:partnerDoes.sessions.n": "2", "keyterms:partnerDoes.case": true, "keyterms:providerDoes.discount": true, "keyterms:providerDoes.discount.disc": "30%", "keyterms:law.state": "California", "keyterms:court.place": "San Francisco County, California", }, }, }; function example(tpl, today) { var e = EXAMPLES[tpl.id] || { parties: [emptyParty(), emptyParty()], values: {} }; var v = defaults(tpl, today); Object.keys(e.values).forEach(function (k) { v[k] = e.values[k]; }); return { values: v, parties: e.parties.map(function (p) { return Object.assign(emptyParty(), p); }) }; } var api = { build: build, defaults: defaults, example: example, fmtDate: fmtDate, isoToday: isoToday, termsText: termsText, fileName: fileName, emptyParty: emptyParty, BLANK: BLANK, DISCLAIMER: DISCLAIMER, CREDIT: CREDIT, LICENCE_URL: LICENCE_URL, EXAMPLES: EXAMPLES }; if (typeof module === "object" && module.exports) module.exports = api; else root.PactCore = api; })(typeof self !== "undefined" ? self : this);