-
+ ${names.map((name) => $h`
+
- ${name} + `)} +
diff --git a/0.47/404.html b/0.47/404.html new file mode 100644 index 0000000..3d2c6b4 --- /dev/null +++ b/0.47/404.html @@ -0,0 +1,1349 @@ + + + +
+ + + + + + + + + + + + + + + + + +export default class Address {
+ constructor(uuid = "", name = "", company = "", street1 = "", street2 = "", zip = "", city = "", state = "", country = "", phone = "", email = "", taxid = "") {
+ this.uuid = uuid;
+ this.name = name;
+ this.company = company;
+ this.street1 = street1;
+ this.street2 = street2;
+ this.zip = zip;
+ this.city = city;
+ this.state = state;
+ this.country = country;
+ this.phone = phone;
+ this.email = email;
+ this.taxid = taxid;
+ this.residential = null;
+ }
+
+ static fromObject(address) {
+ if (address instanceof Address) {
+ return address;
+ }
+ var a = new Address(address.uuid ?? "", address.name, address.company, address.street1,
+ address.street2, address.zip, address.city, address.state, address.country,
+ address.phone, address.email, address.taxid);
+ return a;
+ }
+
+ toStringArray(expandCountry = false) {
+ var citystatezipLine = [this.city, this.state, this.zip].filter(Boolean);
+ var country = this.country == defaultCountryCode() ? "" : this.country;
+ if (expandCountry && country != "") {
+ country = getCountryNameForISO(country);
+ }
+ return [this.name, this.company, this.street1, this.street2, `${citystatezipLine.join(" ")}`, country, (this.taxid ? "Tax ID " + this.taxid : "")].filter(Boolean);
+ }
+
+ /**
+ * Test if the address provided is the same as this address.
+ */
+ equals(address, checkUUID = false) {
+ if (
+ (checkUUID ? this.uuid == address.uuid : true)
+ && this.name == address.name
+ && this.company == address.company
+ && this.street1 == address.street1
+ && this.street2 == address.street2
+ && this.city == address.city
+ && this.state == address.state
+ && this.zip == address.zip
+ && this.country == address.country
+ && this.taxid == address.taxid) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Test if an address is the same delivery point as this address.
+ */
+ dpEquals(address) {
+ if (
+ this.street1 == address.street1
+ && this.street2 == address.street2
+ && this.city == address.city
+ && this.state == address.state
+ && this.zip == address.zip
+ && this.country == address.country) {
+ return true;
+ }
+ return false;
+ }
+}
+This is the source code for global.apis.shipping.getCarrierName and global.apis.shipping.getServiceName.
export function getCarrierName(carrier) {
+ switch (carrier) {
+ case "USPS":
+ case "USPSReturns":
+ case "usps":
+ return "USPS";
+ case "UPS":
+ case "UPSDAP":
+ case "ups":
+ return "UPS";
+ case "FedExDefault":
+ case "FedExSmartPost":
+ case "fedex":
+ return "FedEx";
+ case "DHLExpress":
+ case "dhl_express":
+ return "DHL Express";
+ case "DhlEcs":
+ return "DHL eCommerce";
+ case "SpeedeeAccount":
+ return "Spee-Dee";
+ case "globalpost":
+ return "GlobalPost";
+ case "AccurateAccount":
+ return "Accurate Courier Express";
+ case "ApcAccount":
+ return "APC";
+ case "AsendiaUsaAccount":
+ return "Asendia";
+ case "BetterTrucksAccount":
+ return "Better Trucks";
+ case "BluestreakAccount":
+ return "Blue Streak";
+ case "CanadaPostAccount":
+ case "CanadaPost":
+ return "Canada Post";
+ case "GsoAccount":
+ return "GLS";
+ case "LsoAccount":
+ return "LSO";
+ case "OntracV3Account":
+ return "OnTrac";
+ case "USAExportPBA":
+ return "Asendia";
+ case "FirstChoiceAccount":
+ return "1st Choice Delivery";
+ case "PurolatorAccount":
+ return "Purolator";
+ case "CanparAccount":
+ return "Canpar";
+ case "MaerskAccount":
+ return "Maersk";
+ }
+ if (carrier.endsWith("Account")) {
+ // A lot of EasyPost carriers are the carrier name and the word Account
+ return carrier.replace("Account", "");
+ }
+ return carrier;
+}
+export function getServiceName(serviceId, carrierId = "USPS") {
+ var carrier = getCarrierName(carrierId);
+ switch (serviceId) {
+ // Ambiguous
+ case "":
+ // Used internally if no service ID defined by a plugin or whatever
+ return "";
+ case "Ground":
+ return "Ground";
+ case "Express":
+ if (carrier == "UPS") {
+ return "Worldwide Express";
+ } else if (carrier == "USPS") {
+ return "Priority Mail Express";
+ } else {
+ return "Express";
+ }
+ case "Priority":
+ if (carrier == "USPS") {
+ return "Priority Mail";
+ }
+ return "Priority";
+
+
+ // USPS
+ case "First":
+ case "usps_first_class_mail":
+ case "First-Class Mail":
+ return "First-Class Mail";
+ case "FirstClassMailInternational":
+ case "usps_first_class_mail_international":
+ case "First-Class Mail International":
+ return "First-Class Mail International";
+ case "GroundAdvantage":
+ case "usps_ground_advantage":
+ case "Ground Advantage":
+ return "Ground Advantage";
+ case "MediaMail":
+ case "usps_media_mail":
+ case "Media Mail":
+ return "Media Mail";
+ case "LibraryMail":
+ case "usps_library_mail":
+ case "Library Mail":
+ return "Library Mail";
+ case "usps_priority_mail":
+ case "Priority Mail":
+ return "Priority Mail";
+ case "PriorityMailInternational":
+ case "usps_priority_mail_international":
+ case "Priority Mail International":
+ return "Priority Mail International";
+ case "usps_priority_mail_express":
+ case "Priority Mail Express":
+ return "Priority Mail Express";
+ case "ExpressMailInternational":
+ case "usps_priority_mail_express_international":
+ case "Priority Mail Express International":
+ return "Priority Mail Express International";
+ case "FirstClassPackageInternationalService":
+ case "First-Class Pkg International":
+ return "First-Class Pkg International";
+
+
+ // UPS
+ case "UPSWorldwideExpress":
+ case "ups_worldwide_express":
+ return "Worldwide Express";
+ case "ExpressPlus":
+ case "UPSExpressPlus":
+ case "ups_worldwide_express_plus":
+ return "Worldwide Express Plus";
+ case "Expedited":
+ case "UPSWorldwideExpedited":
+ case "ups_worldwide_expedited":
+ return "Worldwide Expedited";
+ case "UPSWorldwideEconomyDDU":
+ return "Worldwide Economy DDU";
+ case "NextDayAir":
+ case "ups_next_day_air":
+ return "Next Day Air";
+ case "NextDayAirSaver":
+ case "ups_next_day_air_saver":
+ return "Next Day Air Saver";
+ case "NextDayAirEarlyAM":
+ case "ups_next_day_air_early":
+ return "Next Day Air A.M.";
+ case "2ndDayAir":
+ case "ups_2nd_day_air":
+ return "2nd Day Air";
+ case "2ndDayAirAM":
+ case "ups_2nd_day_air_am":
+ return "2nd Day Air A.M.";
+ case "3DaySelect":
+ case "ups_3_day_select":
+ return "3-Day Select";
+ case "ups_ground":
+ return "Ground";
+ case "UPSGroundsaverGreaterThan1lb":
+ return "Ground Saver";
+ case "UPSStandard":
+ case "ups_standard":
+ return "Standard";
+ case "UPSSaver":
+ case "ups_worldwide_saver":
+ return "Worldwide Saver";
+
+
+ // FedEx
+ case "FEDEX_GROUND":
+ case "fedex_ground":
+ return "Ground";
+ case "FEDEX_2_DAY":
+ case "fedex_2day":
+ return "2 Day";
+ case "FEDEX_2_DAY_AM":
+ case "fedex_2day_am":
+ return "2 Day AM";
+ case "FEDEX_EXPRESS_SAVER":
+ case "fedex_express_saver":
+ return "Express Saver";
+ case "STANDARD_OVERNIGHT":
+ case "fedex_standard_overnight":
+ return "Standard Overnight";
+ case "FIRST_OVERNIGHT":
+ case "fedex_first_overnight":
+ return "First Overnight";
+ case "PRIORITY_OVERNIGHT":
+ case "fedex_priority_overnight":
+ return "Priority Overnight";
+ case "INTERNATIONAL_ECONOMY":
+ case "fedex_international_economy":
+ return "International Economy";
+ case "INTERNATIONAL_FIRST":
+ case "fedex_international_first":
+ return "International First";
+ case "FEDEX_INTERNATIONAL_PRIORITY":
+ case "INTERNATIONAL_PRIORITY":
+ case "fedex_international_priority":
+ return "International Priority";
+ case "FEDEX_INTERNATIONAL_PRIORITY_EXPRESS":
+ case "INTERNATIONAL_PRIORITY_EXPRESS":
+ return "International Priority Express";
+ case "FEDEX_INTERNATIONAL_CONNECT_PLUS":
+ case "INTERNATIONAL_CONNECT_PLUS":
+ return "International Connect Plus";
+ case "GROUND_HOME_DELIVERY":
+ case "fedex_home_delivery":
+ return "Ground Home Delivery";
+ case "SMART_POST":
+ return "Ground Economy";
+ case "FEDEX_FIRST_FREIGHT":
+ return "First Overnight Freight";
+ case "FEDEX_1_DAY_FREIGHT":
+ return "1-Day Freight";
+ case "FEDEX_2_DAY_FREIGHT":
+ return "2-Day Freight";
+ case "FEDEX_3_DAY_FREIGHT":
+ return "3-Day Freight";
+ case "INTERNATIONAL_PRIORITY_FREIGHT":
+ return "International Priority Freight";
+ case "INTERNATIONAL_ECONOMY_FREIGHT":
+ return "International Economy Freight";
+
+
+ // USPS Returns
+ case "GroundAdvantageReturn":
+ return "Ground Advantage Return";
+ case "PriorityMailReturn":
+ return "Priority Mail Return";
+ case "PriorityMailExpressReturn":
+ return "Priority Mail Express Return";
+
+
+ // DHL Express
+ case "DomesticEconomySelect":
+ return "Domestic Economy Select";
+ case "DomesticExpress":
+ return "Domestic Express";
+ case "DomesticExpress1030":
+ return "Domestic Express 10:30";
+ case "DomesticExpress1200":
+ return "Domestic Express 12:00";
+ case "EconomySelect":
+ return "Economy Select Document";
+ case "EconomySelectNonDoc":
+ return "Economy Select Non-Document";
+ case "EuroPack":
+ return "EuroPack Document";
+ case "EuropackNonDoc":
+ return "EuroPack Non-Document";
+ case "Express1030":
+ return "10:30 Document";
+ case "Express1030NonDoc":
+ return "10:30 Non-Document";
+ case "Express1200NonDoc":
+ return "12:00 Non-Document";
+ case "Express1200":
+ return "12:00 Document";
+ case "Express900":
+ return "9:00 Document";
+ case "Express900NonDoc":
+ return "9:00 Non-Doc";
+ case "ExpressEasy":
+ return "Easy Document";
+ case "ExpressEasyNonDoc":
+ return "Easy Non-Document";
+ case "ExpressEnvelope":
+ return "Envelope";
+ case "ExpressWorldwide":
+ case "dhl_express_worldwide":
+ return "Worldwide Document";
+ case "ExpressWorldwideB2C":
+ return "Worldwide B2C";
+ case "ExpressWorldwideB2CNonDoc":
+ return "Worldwide B2C Non-Document";
+ case "ExpressWorldwideECX":
+ return "Worldwide ECX";
+ case "ExpressWorldwideNonDoc":
+ return "Worldwide Non-Document";
+
+
+ // DHL eCommerce
+ case "DHLParcelExpedited":
+ return "Parcel Expedited";
+ case "DHLParcelExpeditedMax":
+ return "Parcel Expedited Max";
+ case "DHLParcelGround":
+ return "Parcel Ground";
+ case "DHLBPMExpedited":
+ return "PM Expedited";
+ case "DHLBPMGround":
+ return "PM Ground";
+ case "DHLParcelInternationalDirect":
+ return "Parcel International Direct";
+ case "DHLParcelInternationalStandard":
+ return "Parcel International Standard";
+ case "DHLParcelInternationalDirectSMB":
+ return "Parcel International Direct";
+ case "DHLParcelInternationalStandardSMB":
+ return "Parcel International Standard";
+ case "DHLPacketInternational":
+ return "Packet International";
+ case "DHLParcelInternationalDirectPriority":
+ return "Parcel International Direct Priority";
+ case "DHLParcelInternationalDirectStandard":
+ return "Parcel International Direct Standard";
+
+ // Asendia USA Export
+ case "USAExportStandard":
+ return "USA Export Standard";
+ case "USAExportPlus":
+ return "USA Export Plus";
+ case "USAExportSelect":
+ return "USA Export Select";
+
+ // Spee-Dee
+ case "SpeeDeeDelivery":
+ return "Delivery";
+
+ // GlobalPost
+ case "globalpost_standard_international":
+ return "Standard International";
+ case "globalpost_economy_international":
+ return "Economy International";
+ case "globalpost_plus":
+ return "Plus";
+ case "globalpost_first_class_international":
+ return "First-Class International";
+
+ // Canada Post
+ case "RegularParcel":
+ return "Regular Parcel";
+ case "ExpeditedParcel":
+ return "Expedited Parcel";
+ case "Xpresspost":
+ return "Xpresspost";
+ case "ExpeditedParcelUSA":
+ return "Expedited Parcel USA";
+ case "SmallPacketUSAAir":
+ return "Small Packet USA Air";
+ case "TrackedPacketUSA":
+ return "Tracked Packet USA";
+ case "TrackedPacketUSALVM":
+ return "Tracked Packet USA LVM";
+ case "XpresspostUSA":
+ return "Xpresspost USA";
+ case "XpresspostInternational":
+ return "Xpresspost Int'l";
+ case "InternationalParcelAir":
+ return "Int'l Parcel Air";
+ case "InternationalParcelSurface":
+ return "Int'l Parcel Surface";
+ case "SmallPacketInternationalAir":
+ return "Small Packet Int'l Air";
+ case "SmallPacketInternationalSurface":
+ return "Small Packet Int'l Surface";
+ case "TrackedPacketInternational":
+ return "Tracked Packet Int'l";
+ case "ExpeditedParcelPlus":
+ return "Expedited Parcel Plus";
+
+
+ // GLS US
+ case "EarlyPriorityOvernight":
+ return "Early Priority Overnight";
+ case "PriorityOvernight":
+ return "Priority Overnight";
+ case "CaliforniaParcelService":
+ return "California Parcel";
+ case "SaturdayDeliveryService":
+ return "Saturday Delivery";
+ case "EarlySaturdayService":
+ return "Early Saturday";
+ case "NoonPriorityService":
+ return "Noon Priority";
+
+ // OnTrac
+ case "GRND":
+ return "Ground";
+
+ // LSO
+ case "PriorityEarly":
+ return "Priority Early";
+ case "PriorityBasic":
+ return "Priority Basic";
+ case "Priority2ndDay":
+ return "Priority 2nd Day";
+ case "GroundEarly":
+ return "Ground Early";
+ case "GroundBasic":
+ return "Ground Basic";
+ case "ECommerce":
+ return "ECommerce";
+
+ // Canpar
+ case "USA":
+ return "USA";
+ case "SelectLetter":
+ return "Select Letter";
+ case "SelectPak":
+ return "Select Pak";
+ case "Select":
+ return "Select";
+ case "OvernightLetter":
+ return "Overnight Letter";
+ case "Overnight":
+ return "Overnight";
+ case "USALetter":
+ return "USA Letter";
+ case "USAPak":
+ return "USA Pak";
+ case "SelectUSA":
+ return "Select USA";
+ case "International":
+ return "International";
+
+ // Purolator
+ case "PurolatorExpress":
+ return "Express";
+ case "PurolatorExpress12PM":
+ return "Express 12PM";
+ case "PurolatorExpressPack12PM":
+ return "Express Pack 12PM";
+ case "PurolatorExpressBox12PM":
+ return "Express Box 12PM";
+ case "PurolatorExpressEnvelope12PM":
+ return "Express Envelope 12PM";
+ case "PurolatorExpress1030AM":
+ return "Express 10:30AM";
+ case "PurolatorExpress9AM":
+ return "Express 9AM";
+ case "PurolatorExpressBox":
+ return "Express Box";
+ case "PurolatorExpressBox1030AM":
+ return "Express Box 10:30AM";
+ case "PurolatorExpressBox9AM":
+ return "Express Box 9AM";
+ case "PurolatorExpressBoxEvening":
+ return "Express Box Evening";
+ case "PurolatorExpressBoxInternational":
+ return "Express Box International";
+ case "PurolatorExpressBoxUS":
+ return "Express Box US";
+ case "PurolatorExpressEnvelope":
+ return "Express Envelope";
+ case "PurolatorExpressEnvelope1030AM":
+ return "Express Envelope 10:30AM";
+ case "PurolatorExpressEnvelope9AM":
+ return "Express Envelope 9AM";
+ case "PurolatorExpressEnvelopeEvening":
+ return "Express Envelope Evening";
+ case "PurolatorExpressEnvelopeInternational":
+ return "Express Envelope International";
+ case "PurolatorExpressEnvelopeUS":
+ return "Express Envelope US";
+ case "PurolatorExpressEvening":
+ return "Express Evening";
+ case "PurolatorExpressInternational":
+ return "Express International";
+ case "PurolatorExpressInternational1030AM":
+ return "Express International 10:30AM";
+ case "PurolatorExpressInternational1200":
+ return "Express International 12:00";
+ case "PurolatorExpressInternational9AM":
+ return "Express International 9AM";
+ case "PurolatorExpressBoxInternational1030AM":
+ return "Express Box International 10:30AM";
+ case "PurolatorExpressBoxInternational1200":
+ return "Express Box International 12:00";
+ case "PurolatorExpressBoxInternational9AM":
+ return "Express Box International 9AM";
+ case "PurolatorExpressEnvelopeInternational1030AM":
+ return "Express Envelope International 10:30AM";
+ case "PurolatorExpressEnvelopeInternational1200":
+ return "Express Envelope International 12:00";
+ case "PurolatorExpressEnvelopeInternational9AM":
+ return "Express Envelope International 9AM";
+ case "PurolatorExpressPackInternational1030AM":
+ return "Express Pack International 10:30AM";
+ case "PurolatorExpressPackInternational1200":
+ return "Express Pack International 12:00";
+ case "PurolatorExpressPackInternational9AM":
+ return "Express Pack International 9AM";
+ case "PurolatorExpressPack":
+ return "Express Pack";
+ case "PurolatorExpressPack1030AM":
+ return "Express Pack 10:30AM";
+ case "PurolatorExpressPack9AM":
+ return "Express Pack 9AM";
+ case "PurolatorExpressPackEvening":
+ return "Express Pack Evening";
+ case "PurolatorExpressPackInternational":
+ return "Express Pack International";
+ case "PurolatorExpressPackUS":
+ return "Express Pack US";
+ case "PurolatorExpressUS":
+ return "Express US";
+ case "PurolatorExpressUS1030AM":
+ return "Express US 10:30AM";
+ case "PurolatorExpressUS1200":
+ return "Express US 12:00";
+ case "PurolatorExpressUS9AM":
+ return "Express US 9AM";
+ case "PurolatorExpressBoxUS1030AM":
+ return "Express Box US 10:30AM";
+ case "PurolatorExpressBoxUS1200":
+ return "Express Box US 12:00";
+ case "PurolatorExpressBoxUS9AM":
+ return "Express Box US 9AM";
+ case "PurolatorExpressEnvelopeUS1030AM":
+ return "Express Envelope US 10:30AM";
+ case "PurolatorExpressEnvelopeUS1200":
+ return "Express Envelope US 12:00";
+ case "PurolatorExpressEnvelopeUS9AM":
+ return "Express Envelope US 9AM";
+ case "PurolatorExpressPackUS1030AM":
+ return "Express Pack US 10:30AM";
+ case "PurolatorExpressPackUS1200":
+ return "Express Pack US 12:00";
+ case "PurolatorExpressPackUS9AM":
+ return "Express Pack US 9AM";
+ case "PurolatorGround":
+ return "Ground";
+ case "PurolatorGround1030AM":
+ return "Ground 10:30AM";
+ case "PurolatorGround9AM":
+ return "Ground 9AM";
+ case "PurolatorGround12PM":
+ return "Ground 12PM";
+ case "PurolatorGroundDistribution":
+ return "Ground Distribution";
+ case "PurolatorGroundEvening":
+ return "Ground Evening";
+ case "PurolatorGroundUS":
+ return "Ground US";
+ case "PurolatorQuickShip":
+ return "QuickShip";
+ case "PurolatorQuickShipEnvelope":
+ return "QuickShip Envelope";
+ case "PurolatorQuickShipPack":
+ return "QuickShip Pack";
+ case "PurolatorQuickShipBox":
+ return "QuickShip Box";
+
+
+ // Maersk Parcel
+ case "Maersk-3-Day":
+ return "3 Day";
+
+ }
+
+ console.warn("Unknown shipping service ID: ", serviceId, "Carrier ID:", carrierId);
+
+ // Snipped: code that attempts to format the service ID nicely based on common naming patterns found in the wild.
+
+ return serviceName;
+}
+global.apis.database.getConnection() returns one of these, depending on which database is in use.
export class SQLiteAdapter {
+ constructor(db) {
+ this.type = "sqlite";
+ this.db = db;
+ }
+
+ async query(query, replace) {
+ if (global.devMode) {
+ console.info(query, replace);
+ }
+ return await this.db.all(query, replace);
+ }
+
+ async run(statement, replace) {
+ if (global.devMode) {
+ console.info(statement, replace);
+ }
+ return await this.db.run(statement, replace);
+ }
+
+ async exec(statement) {
+ if (global.devMode) {
+ console.info(statement);
+ }
+ return await this.db.exec(statement);
+ }
+
+ async exists(table, where, replace) {
+ const q = await this.db.all("SELECT EXISTS(SELECT 1 FROM " + table + " WHERE " + where + ") as n", replace);
+ if (q[0].n > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ async close() {
+
+ }
+
+ async tableExists(table) {
+ return (await this.db.get(`SELECT count(name) AS cnt FROM sqlite_master WHERE type='table' AND name=?`, table)).cnt > 0;
+ }
+
+ /**
+ * Get the version code set in the database by setSchemaVersion().
+ */
+ async getSchemaVersion() {
+ var res = await this.db.all(`PRAGMA user_version`);
+ return res[0].user_version;
+ }
+
+ /**
+ * Set the database version, using PRAGMA user_version. Must be an integer.
+ */
+ async setSchemaVersion(version) {
+ await this.db.exec(`PRAGMA user_version = ${version}`);
+ }
+
+}
+export class RemoteDatabaseAdapter {
+ constructor() {
+ this.type = "remote";
+ }
+
+ async apirequest(args) {
+ var resp = await sendToPostalPointHTTPServer(args, "database");
+ if (typeof resp.status == "string" && resp.status == "OK") {
+ return resp.result;
+ } else if (typeof resp.status == "string" && resp.status == "ERR") {
+ if (typeof resp.message == "string") {
+ throw new Error(resp.message);
+ } else {
+ throw new Error(resp);
+ }
+ } else {
+ throw new Error(resp);
+ }
+ }
+
+ async query(query, replace = []) {
+ return await this.apirequest({type: "query", query: query, replace: replace});
+ }
+
+ async run(statement, replace = []) {
+ return await this.apirequest({type: "run", query: statement, replace: replace});
+ }
+
+ async exec(statement) {
+ return await this.apirequest({type: "exec", query: statement});
+ }
+
+ async exists(table, where, replace = []) {
+ return await this.apirequest({type: "exists", table: table, where: where, replace: replace});
+ }
+
+ async close() {
+ // NOOP: We don't care about this
+ }
+
+ async tableExists(table) {
+ return await this.apirequest({type: "tableExists", table: table});
+ }
+
+ async getSchemaVersion() {
+ return await this.apirequest({type: "getSchemaVersion"});
+ }
+
+ async setSchemaVersion(version) {
+ // NOOP: Don't upgrade server's installation, it can do that itself
+ }
+}
+export class MariaDBAdapter {
+ constructor(connection) {
+ this.type = "mariadb";
+ this.conn = connection;
+ }
+
+ async query(query, replace) {
+ if (global.devMode) {
+ console.info(query, replace);
+ }
+ return await this.conn.query(query, replace);
+ }
+
+ async run(statement, replace) {
+ if (global.devMode) {
+ console.info(statement, replace);
+ }
+ return await this.query(statement, replace);
+ }
+
+ async exec(statement) {
+ if (global.devMode) {
+ console.info(statement);
+ }
+ return await this.run(statement);
+ }
+
+ async exists(table, where, replace) {
+ const q = await this.query("SELECT EXISTS(SELECT 1 FROM " + table + " WHERE " + where + ") as n", replace);
+ if (q[0].n > 0) {
+ return true;
+ }
+ return false;
+ }
+
+ async close() {
+ await this.conn.release();
+ }
+
+ async tableExists(table) {
+ return (await this.query("SHOW TABLES LIKE ?", table)).length > 0;
+ }
+
+ /**
+ * Get the version code set in the database by setSchemaVersion(). Returns zero if not set.
+ */
+ async getSchemaVersion() {
+ if (await this.tableExists("database_metadata")) {
+ var res = await this.query("SELECT `value` FROM database_metadata WHERE `key`='schema_version' LIMIT 1");
+ console.log(res);
+ console.log(res[0].value);
+ if (res.length == 1) {
+ return res[0].value;
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Set a version number for the database schema.
+ * Must be an integer to maintain code compatibility with SQLite driver.
+ * Will create a "database_metadata" table if required to store the version number.
+ */
+ async setSchemaVersion(version) {
+ if (await this.tableExists("database_metadata")) {
+ await this.query("REPLACE INTO `database_metadata` (`key`, `value`) VALUES (?, ?)", ["schema_version", version]);
+ } else {
+ await this.exec("CREATE TABLE IF NOT EXISTS `database_metadata` ( `key` VARCHAR(50) NOT NULL, `value` VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY (`key`))");
+ await this.setSchemaVersion(version);
+ }
+ }
+}
+Plugins can use global.apis.eventbus to receive events when certain actions happen in PostalPoint.
barcodeScanned: Contents of a barcode that was just scanned, as a string. String also contains any non-printing characters in the barcode.browserCloseRequest: The embedded web browser listens for this event, and closes itself when received.browserNavigate: Contains the URL the embedded web browser just navigated to.sendToCustomerScreen: Emit to send data via window.postMessage to a custom HTML interface on the customer-facing display.receiveFromCustomerScreen: Contains the event sent from the customer-facing display's custom HTML interface via window.parent.postMessagetransactionFinished: Contains a receipt object of a transaction that was just finalized. See below for event data details.customerSignatureCollected: Contains a signature image from the customer-facing display. See below for event data details.settingsSaved: Emitted when PostalPoint's settings are saved. Usually this means the user changed a setting in the UI.pluginSettingsSaved: Emitted when the user saves a plugin's settings. The plugin ID string is sent as the event data.packageCheckIn: Emitted when a package is checked in to a mailbox or for Hold At Location. See below for event data details.mailboxMailDelivered: Emitted when mail delivery notifications are sent by the user. Data is an array of the mailbox numbers notifications are being sent for.// Handle a barcode scan.
+// Remember that PostalPoint will probably also be doing something in response to the barcode.
+global.apis.eventbus.on("barcodeScanned", function (barcodedata) {
+ // do something with the barcode
+});
+
+// Close the embedded web browser, returning the user to whatever was onscreen before it opened
+global.apis.eventbus.emit("browserCloseRequest");
+For events that return an object instead of a single value.
+See Receipt
+{
+ tag: "abcxyz123456", // Unique ID for the package, also found in the shelf label barcode.
+ tracking: "94001...", // Package tracking number. May be an empty string for items without tracking.
+ carrier: "FedEx", // Package carrier name, if detectable from the tracking number. Otherwise an empty string.
+ mailbox: "123", // Mailbox number. Will be "HAL" for Hold At Location packages.
+ isHAL: false, // True if package is for Hold At Location.
+ recipient: "", // Hold At Location recipient name, or empty string if not HAL.
+ toLocker: "5", // Parcel locker number, or false if not going to a parcel locker.
+ shelfLabelPrinted: true // Indicates if a shelf label was printed for this package. Will be false if going to a locker, if the user requested no label, or if the label failed to print.
+}
+export class FormPS1583 {
+ constructor() {
+ this.formRevision = LATEST_FORM_REVISION; // Currently "June2024"
+ this.pmbOpenedDate = new Date();
+ this.pmbClosedDate = null;
+ this.cmraStreetAddress = getSetting("origin_street1");
+ this.pmbNumber = "";
+ this.cmraZIP = getSetting("origin_zip");
+ var cmraZIPData = getZIP(this.cmraZIP);
+ if (cmraZIPData) {
+ this.cmraCity = cmraZIPData.city;
+ this.cmraState = cmraZIPData.state;
+ } else {
+ this.cmraCity = getSetting("origin_city", "");
+ this.cmraState = getSetting("origin_state", "");
+ }
+ this.serviceTypeBusiness = false; // true for business PMB, false for residential
+ this.applicant = {
+ firstName: "",
+ lastName: "",
+ middleName: "",
+ phone: "",
+ email: "",
+ streetAddress: "",
+ city: "",
+ state: "",
+ zip: "",
+ country: "",
+ courtProtected: false,
+ photoID: {
+ name: "",
+ number: "",
+ issuer: "",
+ expirationDate: null,
+ type: null // "DL/ID", "UniformedService", "USAccess", "USUni",
+ // "Passport", "Matricula", "NEXUS",
+ // "CertOfNaturalization", "USPermResident"
+ },
+ addressID: {
+ name: "",
+ streetAddress: "",
+ city: "",
+ state: "",
+ zip: "",
+ country: "",
+ type: null, // "DL/ID", "Lease", "Mortgage", "Insurance", "VehicleReg", "Voter"
+ expirationDate: null // Optional currently but must be kept current - Oct 2025
+ }
+ };
+ this.authorizedIndividual = {
+ firstName: "",
+ lastName: "",
+ middleName: "",
+ phone: "",
+ email: "",
+ streetAddress: "",
+ city: "",
+ state: "",
+ zip: "",
+ country: "",
+ photoID: {
+ name: "",
+ number: "",
+ issuer: "",
+ expirationDate: null,
+ type: null // "DL/ID", "UniformedService", "USAccess", "USUni",
+ // "Passport", "Matricula", "NEXUS",
+ // "CertOfNaturalization", "USPermResident"
+ },
+ addressID: {
+ name: "",
+ streetAddress: "",
+ city: "",
+ state: "",
+ zip: "",
+ country: "",
+ type: null, // "DL/ID", "Lease", "Mortgage", "Insurance", "VehicleReg", "Voter"
+ expirationDate: null // Optional currently but must be kept current - Oct 2025
+ }
+ };
+ this.mailTransferredTo = {
+ streetAddress: "",
+ city: "",
+ state: "",
+ zip: "",
+ country: "",
+ phone: "",
+ email: ""
+ };
+ this.business = {
+ name: "",
+ type: "",
+ streetAddress: "",
+ city: "",
+ state: "",
+ zip: "",
+ country: "",
+ phone: "",
+ placeOfRegistration: ""
+ };
+ this.additionalRecipients = []; // Array of strings containing names
+ this.applicantSignature = ""; // PNG image data URI
+ this.applicantSignatureDate = null;
+ this.cmraSignature = ""; // PNG image data URI
+ this.cmraSignatureDate = null;
+ this.hasForwardingAddress = false;
+ }
+
+ getTermsAndConditions() {
+ return DEFAULT_TERMS_CONDITIONS[this.formRevision];
+ }
+
+ getApplicantForwardingAddress() {
+ if (this.mailTransferredTo.streetAddress != "") {
+ return new Address(null,
+ [this.applicant.firstName, this.applicant.lastName].filter(Boolean).join(" "),
+ this.business.name ?? "",
+ this.mailTransferredTo.streetAddress,
+ "",
+ this.mailTransferredTo.zip,
+ this.mailTransferredTo.city,
+ this.mailTransferredTo.state,
+ this.mailTransferredTo.country ?? "US",
+ this.mailTransferredTo.phone ?? "",
+ this.mailTransferredTo.email ?? ""
+ );
+ }
+ return new Address(null,
+ [this.applicant.firstName, this.applicant.lastName].filter(Boolean).join(" "),
+ this.business.name ?? "",
+ this.applicant.streetAddress,
+ "",
+ this.applicant.zip,
+ this.applicant.city,
+ this.applicant.state,
+ this.applicant.country ?? "US",
+ this.applicant.phone ?? "",
+ this.applicant.email ?? ""
+ );
+ }
+
+ getFormFields() {
+ var fields = FORM_FIELDS[this.formRevision];
+ function getNestedValue(obj, path) {
+ return path.split('.').reduce((o, key) => (o ? o[key] : ""), obj);
+ }
+ var outfields = [];
+ var groupheading = {};
+ var groupfields = [];
+ for (var prop in fields) {
+ if (fields[prop].t == "heading") {
+ if (groupfields.length > 0) {
+ groupheading.fields = groupfields;
+ outfields.push(groupheading);
+ groupfields = [];
+ }
+ groupheading = {
+ heading: fields[prop].l,
+ groupid: fields[prop].group ?? null,
+ fields: []
+ };
+ }
+ fields[prop].n = prop;
+ fields[prop].v = getNestedValue(this, prop);
+ if (typeof fields[prop].v == "undefined" || fields[prop].v == null) {
+ fields[prop].v = "";
+ }
+ if (fields[prop].t == "date") {
+ if (fields[prop].v instanceof Date) {
+ // Cancel out the timezone in the date object
+ // If we don't do this, the dates will be subtracted by one day each time we load
+ // https://stackoverflow.com/a/17329571
+ fields[prop].v.setTime(fields[prop].v.getTime() + fields[prop].v.getTimezoneOffset() * 60 * 1000);
+ }
+ fields[prop].v = formatTimestamp("Y-m-d", fields[prop].v);
+ if (fields[prop].v == "1969-12-31" || fields[prop].v == "1970-01-01") {
+ fields[prop].v = "";
+ }
+ }
+ if (fields[prop].t == "select" && typeof fields[prop].b == "boolean") {
+ fields[prop].v = fields[prop].v ? "true" : "";
+ }
+ if (fields[prop].t != "heading") {
+ groupfields.push(fields[prop]);
+ }
+ }
+ if (groupfields != []) {
+ groupheading.fields = groupfields;
+ outfields.push(groupheading);
+ }
+ return outfields;
+ }
+
+ static fromHTMLFormData(formdata, revision = LATEST_FORM_REVISION) {
+ var f = new FormPS1583();
+
+ function setNestedValue(obj, path, value) {
+ const keys = path.split('.');
+ const lastKey = keys.pop();
+ const target = keys.reduce((o, key) => {
+ if (o[key] === undefined)
+ o[key] = {};
+ return o[key];
+ }, obj);
+ if (typeof FORM_FIELDS[revision][path].b == "boolean") {
+ target[lastKey] = (value == "true" || value == true);
+ } else {
+ target[lastKey] = value;
+ }
+ }
+
+ for (var prop in formdata) {
+ setNestedValue(f, prop, formdata[prop]);
+ }
+
+ return f;
+ }
+
+ static fromJSON(o) {
+ var f = new FormPS1583();
+ f.formRevision = o.formRevision ?? LATEST_FORM_REVISION;
+ f.pmbOpenedDate = new Date(o.pmbOpenedDate);
+ f.pmbClosedDate = o.pmbClosedDate ? new Date(o.pmbClosedDate) : null;
+ f.cmraStreetAddress = o.cmraStreetAddress;
+ f.pmbNumber = o.pmbNumber;
+ f.cmraCity = o.cmraCity;
+ // snip, see constructor for full data structure
+ return f;
+ }
+
+ toJSON() {
+ return {
+ formRevision: this.formRevision,
+ pmbOpenedDate: this.pmbOpenedDate,
+ pmbClosedDate: this.pmbClosedDate,
+ cmraStreetAddress: this.cmraStreetAddress,
+ pmbNumber: this.pmbNumber,
+ cmraCity: this.cmraCity,
+ // snip, see constructor for full data structure
+ };
+ }
+
+ /**
+ * Render this form to PDF
+ * @returns PDF bytes
+ */
+ async getPDF() {
+ // snip, it draws the form contents onto a PDF using the pdf-lib library
+ // If you really want to see how, email us for the code
+ return await document.save();
+ }
+}
+This object is supplied a plugin registered with registerRateEndpoint when PostalPoint requests
+shipping rates from the plugin.
export class Package {
+ constructor(isPrepaid = false) {
+ this.prepaid = isPrepaid;
+ this.packaging = {
+ type: "Parcel",
+ service: "",
+ carrier: "",
+ length: 999999,
+ width: 999999,
+ height: 999999,
+ weightOz: 999999,
+ nonmachinable: false,
+ additionalHandling: false,
+ internalid: 100,
+ oversizeFlag: false
+ };
+ this.extraServices = {
+ certifiedMail: false,
+ barcode3800: "",
+ registeredMail: false,
+ registeredMailAmount: false, // can be a number in USD
+ returnReceipt: false,
+ returnReceiptElectronic: false,
+ insurance: false, // can be a number in USD
+ signature: false, // can be false, "SIGNATURE", or "SIGNATURE_RESTRICTED"
+ hazmat: false,
+ perishable: false,
+ crematedRemains: false,
+ liveAnimal: false, // BEES, DAY_OLD_POULTRY, ADULT_BIRDS, OTHER_LIVES
+ cod: false, // Collect on Delivery
+ codAmount: false,
+ endorsement: "", // ADDRESS_SERVICE_REQUESTED, CHANGE_SERVICE_REQUESTED, FORWARDING_SERVICE_REQUESTED, LEAVE_IF_NO_RESPONSE, RETURN_SERVICE_REQUESTED
+ carrier_billing_account: {// Bill a third party's account number for the label
+ type: "", // "" (ignores this entire option), "SENDER" (EasyPost default), "THIRD_PARTY", "RECEIVER", "COLLECT"
+ carrier: "", // Carrier ID (should be used to filter rates)
+ account_number: "", // Carrier account number to bill
+ country: "", // Country account is based in
+ postal_code: "" // Postal code of account
+ },
+ dryIce: false,
+ dryIceWeight: 0,
+ dryIceMedical: false
+ };
+ this.description = ""; // Fillable on customs form, or generated before rating call using customs items
+ this.specialRateEligibility = false;
+ this.customs = {
+ contents: "",
+ contentsExplanation: "", // needed if contents is "other", will be copied from this.description if blank for maximum carrier compatibility
+ signature: "",
+ restriction: "",
+ restrictionComments: "", // needed if restriction is "other"
+ nonDelivery: "return", // "return" or "abandon",
+ eel_pfc: "",
+ items: [] // {index: 0, description: "", qty: "", lbs: "", oz: "", value: "", hscode: "", origin: US"}
+ };
+ this.toAddress = new Address();
+ this.returnAddress = new Address();
+ this.originAddress = new Address();
+ this.trackingNumber = "";
+ }
+
+ /**
+ * Format as EasyPost shipment object
+ * @returns {Package.toEasyPostShipment.shipment}
+ */
+ async toEasyPostShipment() {
+ // Not relevant to plugins
+ }
+
+ /**
+ * Format as Endicia shipment object
+ * @returns {Package.toSERAShipment.shipment}
+ */
+ async toSERAShipment() {
+ // Not relevant to plugins
+ }
+
+ /**
+ * Get a human-readable summary of size and options.
+ * Does not include address data.
+ * @returns {String}
+ */
+ async toString() {
+ let summary = [];
+ let packaging = await getPackagingByID(this.packaging.internalid);
+ let weight = ozToLbsOz(this.packaging.weightOz);
+ let weightStr = this.packaging.weightOz >= 16 ? `${weight[0]} lbs ${weight[1]} oz` : `${weight[1]} oz`;
+ if (packaging != false) {
+ if (packaging.irregular) {
+ if (packaging.weight === false) {
+ summary.push("Parcel");
+ } else {
+ summary.push(`${weightStr} Parcel`);
+ }
+ summary.push("Additional Handling");
+ } else {
+ if (packaging.weight === false) {
+ summary.push(packaging.name);
+ } else {
+ summary.push(`${weightStr} ${packaging.name}`);
+ }
+ }
+ } else {
+ summary.push(weightStr);
+ }
+ if (this.extraServices.hazmat) {
+ summary.push("HAZMAT");
+ }
+ if (this.extraServices.liveAnimal === true) {
+ summary.push("Live Animals");
+ } else if (typeof this.extraServices.liveAnimal == "string") {
+ switch (this.extraServices.liveAnimal) {
+ case "BEES":
+ summary.push("Live Bees");
+ break;
+ case "DAY_OLD_POULTRY":
+ summary.push("Day-old Poultry");
+ break;
+ case "ADULT_BIRDS":
+ summary.push("Live Adult Birds");
+ break;
+ case "OTHER_LIVES":
+ default:
+ summary.push("Live Animals");
+ break;
+ }
+ }
+ if (this.extraServices.perishable) {
+ summary.push("Perishable");
+ }
+ if (this.extraServices.crematedRemains) {
+ summary.push("Cremated Remains");
+ }
+ if (this.extraServices.certifiedMail) {
+ summary.push("Certified Mail");
+ } else if (this.extraServices.registeredMail) {
+ summary.push("Registered Mail");
+ summary.push("Registered for $" + (this.extraServices.registeredMailAmount * 1.0).toFixed(2));
+ } else if (this.extraServices.signature == "SIGNATURE") {
+ summary.push("Signature Required");
+ }
+ if (this.extraServices.signature == "ADULT_SIGNATURE") {
+ summary.push("Adult Signature Required");
+ }
+ if (this.extraServices.signature == "SIGNATURE_RESTRICTED") {
+ summary.push("Restricted Delivery");
+ }
+ if (this.extraServices.returnReceiptElectronic) {
+ summary.push("Return Receipt Electronic");
+ }
+ if (this.extraServices.returnReceipt) {
+ summary.push("Return Receipt");
+ }
+ if (this.extraServices.insurance) {
+ summary.push("Insured for $" + (this.extraServices.insurance * 1.0).toFixed(2));
+ }
+ if (this.extraServices.cod) {
+ summary.push("Collect on Delivery: $" + (this.extraServices.codAmount * 1.0).toFixed(2));
+ }
+ if (this.extraServices.dryIce && this.extraServices.dryIceWeight > 0) {
+ summary.push("Dry Ice: " + (this.extraServices.dryIceWeight * 1).toFixed(0) + " oz");
+ }
+ if (this.extraServices.carrier_billing_account?.type) {
+ if (this.extraServices.carrier_billing_account.type != "") {
+ var accountNumber = this.extraServices.carrier_billing_account.account_number;
+ var accountNumberCensored = accountNumber.substring(accountNumber.length - 4).padStart(accountNumber.length, "X");
+ var carrierName = this.extraServices.carrier_billing_account.carrier;
+ switch (this.extraServices.carrier_billing_account.type) {
+ case "SENDER":
+ summary.push(`Bill to sender ${carrierName} account #${accountNumberCensored}`);
+ break;
+ case "THIRD_PARTY":
+ summary.push(`Bill to third party ${carrierName} account #${accountNumberCensored}`);
+ break;
+ case "RECEIVER":
+ summary.push(`Bill to receiver ${carrierName} account #${accountNumberCensored}`);
+ break;
+ case "COLLECT":
+ if (accountNumber.length > 0) {
+ summary.push(`Bill collect ${carrierName} account #${accountNumberCensored}`);
+ } else {
+ summary.push(`Bill collect`);
+ }
+ break;
+ }
+ }
+ }
+ return summary.join("\n");
+ }
+
+ async needsHAZMATPrompt() {
+ try {
+ let packagingInfo = await getPackagingByID(this.packaging.internalid);
+ if (packagingInfo.hazmat) {
+ return true;
+ }
+ if (this.packaging.weight > 10) {
+ return true;
+ }
+ if (packagingInfo.l >= -1 && Math.max(this.packaging.length, this.packaging.width, this.packaging.height) > 0.5) {
+ return true;
+ }
+ switch (packagingInfo.type) {
+ case "Letter":
+ case "Card":
+ return false;
+ }
+ return true;
+ } catch (ex) {
+ return true;
+ }
+ }
+
+ get isPrepaid() {
+ return this.prepaid == true;
+ }
+
+ setCustomsInfo(contents, contentsExplanation, signature, restriction, restrictionComments, nonDelivery) {
+ let items = this.customs.items; // Save this and copy it back in so we don't overwrite it
+ this.customs = {
+ contents: contents,
+ contentsExplanation: contentsExplanation, // needed if contents is "other"
+ signature: signature,
+ restriction: restriction,
+ restrictionComments: restrictionComments, // needed if restriction is "other"
+ nonDelivery: nonDelivery, // "return" or "abandon",
+ items: items
+ };
+ }
+
+ /**
+ * Get the customs items, ignoring any that are blank.
+ * @returns {Array}
+ */
+ getCustomsItems() {
+ let items = [];
+ for (let i = 0; i < this.customs.items.length; i++) {
+ let item = this.customs.items[i];
+ if (item.description == "" && (item.qty == "" || item.qty == 0) && (item.weight == "" || item.weight == 0) && (item.value == "" || item.value == 0)) {
+ continue;
+ }
+ items.push(item);
+ }
+ return items;
+ }
+
+ setCustomsItems(items) {
+ this.customs.items = items;
+ }
+
+ getCustoms() {
+ this.customs.items = this.getCustomsItems();
+ return this.customs;
+ }
+
+ /**
+ * Attempt to automatically fix simple issues like overweight letters.
+ * @returns {undefined}
+ */
+ async fixIssues() {
+ if (this.packaging.type == "Letter" && this.packaging.weightOz > 3.5) {
+ if (this.packaging.nonmachinable) {
+ return; // Has to be a parcel, can't fix without dimensions
+ }
+ this.packaging.type = "Flat";
+ this.packaging.internalid = 104;
+ }
+ }
+
+ /**
+ * Do some basic checks to see if this package is even remotely shippable
+ * @param {boolean} kioskMode If true, returned strings are suitable for display in kiosk mode.
+ * @returns {boolean|string} true if okay, human-readable error message and instructions if not okay
+ */
+ async isValid(kioskMode = false) {
+ // Removed from docs for brevity. Just a bunch of if statements to catch problems.
+ }
+
+ /**
+ * Set package characteristics
+ * @param {string} type "Parcel", "Letter", "Flat", "Card"
+ * @param {type} service
+ * @param {type} carrier
+ * @param {type} length
+ * @param {type} width
+ * @param {type} height
+ * @param {type} weightOz
+ * @returns {undefined}
+ */
+ setPackaging(type, service, carrier, length, width, height, weightOz, nonmachinable) {
+ if (typeof nonmachinable == "undefined") {
+ nonmachinable = false;
+ }
+ if (type == "Card") {
+ // Postcards
+ weightOz = 1;
+ this.packaging.internalid = 105;
+ } else if (type == "Flat") {
+ this.packaging.internalid = 104;
+ } else if (type == "Letter") {
+ this.packaging.internalid = 102;
+ if (nonmachinable) {
+ this.packaging.internalid = 103;
+ }
+ }
+ this.packaging.type = type;
+ this.packaging.service = service;
+ this.packaging.carrier = carrier;
+ this.packaging.weightOz = weightOz;
+ this.packaging.nonmachinable = nonmachinable;
+
+ // Enforce Length > Width > Height
+ let size = [length, width, height];
+ size.sort(function (a, b) {
+ return b - a;
+ });
+ this.packaging.length = size[0];
+ this.packaging.width = size[1];
+ this.packaging.height = size[2];
+ }
+
+ /**
+ * Set an extra service
+ * @param {string} id Service ID
+ * @param {boolean} enabled Turn it on or off
+ * @param {string} value Service value, if needed (some are not just a boolean)
+ * @returns {undefined}
+ */
+ setExtraService(id, enabled, value) {
+ if (typeof value != "undefined" && enabled) {
+ this.extraServices[id] = value;
+ } else {
+ this.extraServices[id] = enabled == true;
+ }
+ }
+
+ getExtraServices() {
+ return this.extraServices;
+ }
+
+ /**
+ * Set to "MEDIA_MAIL", "LIBRARY_MAIL", or false
+ * @param {type} rate
+ * @returns {undefined}
+ */
+ set specialRate(rate) {
+ if (rate == "MEDIA") {
+ rate = "MEDIA_MAIL";
+ } else if (rate == "LIBRARY") {
+ rate = "LIBRARY_MAIL";
+ }
+ if (rate != "MEDIA_MAIL" && rate != "LIBRARY_MAIL") {
+ rate = false;
+ }
+ this.specialRateEligibility = rate;
+ }
+
+ get specialRate() {
+ return this.specialRateEligibility;
+ }
+
+ /**
+ * Save an address to this package.
+ * @param {string} type "to", "return", or "origin"
+ * @param {string} name
+ * @param {string} company
+ * @param {string} street1
+ * @param {string} street2
+ * @param {string} city
+ * @param {string} state
+ * @param {string} zip
+ * @param {string} country ISO 2-char country code
+ * @param {string} phone
+ * @param {string} email
+ * @returns {undefined}
+ */
+ setAddress(type, name, company, street1, street2, city, state, zip, country, phone, email) {
+ let address = Address.fromObject({
+ name: name,
+ company: company,
+ street1: street1,
+ street2: street2,
+ city: city,
+ state: state,
+ zip: zip,
+ country: country,
+ phone: phone,
+ email: email
+ });
+ switch (type) {
+ case "to":
+ this.toAddress = address;
+ break;
+ case "return":
+ this.returnAddress = address;
+ break;
+ case "origin":
+ this.originAddress = address;
+ break;
+ }
+ }
+
+ /**
+ * Set an address using an object that matches the internal form (see setAddress())
+ * @param {string} type
+ * @param {object} data
+ * @returns {undefined}
+ */
+ setAddressWhole(type, address) {
+ switch (type) {
+ case "to":
+ this.toAddress = Address.fromObject(address);
+ break;
+ case "return":
+ this.returnAddress = Address.fromObject(address);
+ break;
+ case "origin":
+ this.originAddress = Address.fromObject(address);
+ break;
+ }
+ }
+
+ get tracking() {
+ return this.trackingNumber;
+ }
+
+ set tracking(n) {
+ this.trackingNumber = n;
+ }
+
+ /**
+ * Get the "from" address that will be shown,
+ * using the return address or origin address as needed
+ * @returns {address}
+ */
+ getReturnAddress() {
+ var a = null;
+ if (typeof this.returnAddress == "object") {
+ a = Address.fromObject(this.returnAddress);
+ } else {
+ a = Address.fromObject(this.originAddress);
+ }
+ if (a.country == "") {
+ a.country = defaultCountryCode();
+ }
+ return a;
+ }
+
+ getToAddress() {
+ var a = Address.fromObject(this.toAddress);
+ if (a.country == "") {
+ a.country = defaultCountryCode();
+ }
+ return a;
+ }
+
+ getFromAddress() {
+ var a = null;
+ if (typeof this.originAddress == "object") {
+ a = Address.fromObject(this.originAddress);
+ } else {
+ a = Address.fromObject(this.returnAddress);
+ }
+ if (a.country == "") {
+ a.country = defaultCountryCode();
+ }
+ return a;
+ }
+}
+This is an example of the data global.apis.pos.onReceiptChange
+and global.apis.pos.onTransactionFinished send to plugins.
+All data for a PostalPoint transaction is available in its receipt object.
The money-related properties near the bottom of this sample are generated by PostalPoint +from the items and payments.
+due property will be a negative number if change is owed to the customer.pendingEmailTo is set to a suggested email address for the email receipt, and if the receipt
+should actually be emailed, it will be set in emailTo.uuid is a unique 16-character alphanumeric receipt ID number, which is shown and used in several places.
+The uuid is generated using global.apis.util.uuid.short().customerAccountId is the UUID for the customer's account, or null if there isn't a customer attached.{
+ "items": [
+ ReceiptItem.fromJSON({
+ "id": "9100123456789012345678",
+ "label": "Test Package",
+ "text": "Package Details\nTracking # 9100 1234 5678 9012 3456 78\nTo:\nTEST PERSON\nORGANIZATION INC\n123 TEST ROAD\nTESTTOWN TE 99999-0001",
+ "priceEach": 8,
+ "qty": 1,
+ "cost": 0,
+ "retail": 8,
+ "taxRate": 0,
+ "free": false,
+ "barcode": "9100123456789012345678",
+ "certifiedInfo": false,
+ "isMerch": false,
+ "surcharge": false,
+ "toAddress": {
+ "name": "TEST PERSON",
+ "company": "ORGANIZATION INC",
+ "street1": "123 TEST ROAD",
+ "street2": null,
+ "city": "TESTTOWN",
+ "state": "TE",
+ "zip": "99999-0001",
+ "email": null,
+ "phone": null,
+ "country": "US"
+ },
+ "fromAddress": {
+ "name": "TEST PERSON",
+ "company": "ORGANIZATION INC",
+ "street1": "123 TEST ROAD",
+ "street2": null,
+ "city": "TESTTOWN",
+ "state": "TE",
+ "zip": "99999-0001",
+ "email": null,
+ "phone": null,
+ "country": "US"
+ }
+ }),
+ ReceiptItem.fromJSON({
+ "id": "testitem",
+ "label": "Test Item",
+ "text": "",
+ "priceEach": 2,
+ "qty": 1,
+ "cost": 0,
+ "retail": 2,
+ "taxRate": 0.1,
+ "free": false,
+ "barcode": "",
+ "certifiedInfo": false,
+ "isMerch": true,
+ "surcharge": false
+ })
+ ],
+ "payments": [
+ ReceiptPayment.fromJSON({
+ "amount": 10,
+ "type": "cash",
+ "text": "",
+ "id": "testcash"
+ })
+ ],
+ "subtotal": 10,
+ "subtotalFormatted": "$10.00",
+ "tax": 0.2,
+ "taxFormatted": "$0.20",
+ "grandTotal": 10.2,
+ "grandTotalFormatted": "$10.20",
+ "paid": 10.2,
+ "paidFormatted": "$10.20",
+ "due": 0,
+ "dueFormatted": "$0.00",
+ "emailTo": null,
+ "pendingEmailTo": null,
+ "uuid": "1234567890abcdef",
+ "customerAccountId": null,
+ "topTextHTML": "",
+ "bottomTextHTML": ""
+}
+export class ReceiptItem {
+ /**
+ *
+ * @param {string|number} id Unique ID number for this item (UPC code, inventory number, etc). Used to deduplicate line items. Unique items (like shipping labels) should be random or empty.
+ * @param {string} label One-line item information.
+ * @param {string} text Extra item information.
+ * @param {number} priceEach Price per unit
+ * @param {number} quantity Number of units
+ * @param {number} cost Cost per unit. Used for automatic expense tracking.
+ * @param {number} taxrate Examples: 0 (for 0%), 0.05 (for 5%), etc
+ * @param {string} taxableAmount The part of the sale price that's taxable. "" for default (all), "markup" for only taxing profit.
+ * @returns {ReceiptItem}
+ */
+ constructor(id, label, text, priceEach, quantity, cost, taxrate = 0.0, taxableAmount = "") {
+ this.id = id;
+ this.label = label;
+ if (text == null) {
+ this.txt == "";
+ } else {
+ this.txt = text;
+ }
+ this.priceEach = num(priceEach);
+ this.qty = num(quantity);
+ this.cost = num(cost);
+ if (isNaN(taxrate)) {
+ this.taxRate = 0;
+ } else {
+ this.taxRate = num(taxrate);
+ }
+ this.taxableAmount = taxableAmount;
+ this.merch = false;
+ this.merchid = null;
+ this.surcharge = false;
+ this.retail = 0; // For ensuring PostalPoint fee collection on office mode shipments
+ this.mailboxNumber = null;
+ this.mailboxDays = 0;
+ this.mailboxMonths = 0;
+ this.category = ""; // merch category
+ this.electronicReturnReceipt = false;
+ }
+
+ static fromJSON(obj) {
+ var item = new ReceiptItem(obj.id, obj.label, obj.text, obj.priceEach, obj.qty, obj.cost, obj.taxRate, obj.taxableAmount ?? "");
+ item.free = obj.free;
+ item.barcode = obj.barcode;
+ item.certifiedInfo = obj.certifiedInfo;
+ item.toAddress = obj.toAddress;
+ item.fromAddress = obj.fromAddress;
+ item.merch = obj.isMerch == true || (typeof obj.merchid == "string" && obj.merchid.length > 0);
+ item.merchid = obj.merchid ?? null;
+ item.mailboxNumber = obj.mailboxNumber ?? null;
+ item.mailboxDays = obj.mailboxDays ?? 0;
+ item.mailboxMonths = obj.mailboxMonths ?? 0;
+ item.surcharge = obj.surcharge;
+ item.retailPrice = obj.retail;
+ item.carrier = obj.carrier ?? null;
+ item.service = obj.service ?? null;
+ item.category = obj.category ?? "";
+ item.electronicReturnReceipt = obj.electronicReturnReceipt ?? false;
+ return item;
+ }
+
+ toJSON() {
+ return {
+ id: this.id,
+ label: this.label,
+ text: this.text,
+ priceEach: num(this.priceEach),
+ qty: num(this.qty),
+ cost: num(this.cost),
+ retail: num(this.retail),
+ taxRate: num(this.taxRate),
+ taxableAmount: this.taxableAmount,
+ taxTotal: this.taxAmount,
+ free: this.free,
+ barcode: this.barcode,
+ certifiedInfo: this.certifiedInfo,
+ isMerch: this.merch,
+ merchid: this.merchid,
+ surcharge: this.surcharge,
+ toAddress: this.toAddress,
+ fromAddress: this.fromAddress,
+ mailboxNumber: this.mailboxNumber,
+ mailboxDays: this.mailboxDays,
+ mailboxMonths: this.mailboxMonths,
+ carrier: this.carrier,
+ service: this.service,
+ category: this.category,
+ electronicReturnReceipt: this.electronicReturnReceipt
+ };
+ }
+
+ get text() {
+ if (typeof this.txt == "string") {
+ return this.txt;
+ }
+ return "";
+ }
+
+ set text(t) {
+ if (typeof t == "string") {
+ this.txt = t;
+ } else {
+ this.txt = "";
+ }
+ }
+
+ get certifiedInfo() {
+ if (typeof this.certified == "undefined") {
+ return false;
+ }
+ return this.certified;
+ }
+
+ set certifiedInfo(info) {
+ this.certified = info;
+ }
+
+ setCertifiedInfo(tracking, certfee, extrafees, postage, date, location, toaddress) {
+ this.certified = {
+ tracking: tracking,
+ certifiedFee: num(certfee),
+ extraFees: extrafees,
+ postage: num(postage),
+ date: date,
+ location: location,
+ to: toaddress
+ };
+ }
+
+ setQuantity(q) {
+ this.qty = num(q);
+ }
+
+ get free() {
+ return this.isFree == true;
+ }
+
+ set free(free) {
+ this.isFree = free == true;
+ }
+
+ get barcode() {
+ if (typeof this.barcodeData != "string") {
+ return "";
+ }
+ return this.barcodeData;
+ }
+
+ set barcode(data) {
+ this.barcodeData = data;
+ }
+
+ get linePrice() {
+ return round(m(this.priceEach, this.qty), 2);
+ }
+
+ get priceEachFormatted() {
+ return getCurrencySymbol() + round(num(this.priceEach), 2).toFixed(2);
+ }
+
+ get linePriceFormatted() {
+ return getCurrencySymbol() + round(num(this.linePrice), 2).toFixed(2);
+ }
+
+ get texthtml() {
+ if (typeof this.text != "string") {
+ return "";
+ }
+ var lines = this.text.split("\n");
+ for (var i = 0; i < lines.length; i++) {
+ if (lines[i].startsWith("Tracking # ")) {
+ // Allow copying tracking number
+ lines[i] = "Tracking # <span class=\"usall\">" + lines[i].replace("Tracking # ", "") + "</span>";
+ }
+ }
+ return lines.join("<br />");
+ }
+
+ get taxAmount() {
+ if (this.taxableAmount == "markup") {
+ var lineCost = m(this.cost, this.qty);
+ var margin = s(this.linePrice, lineCost);
+ if (margin <= 0) {
+ return 0;
+ }
+ return round(m(margin, this.taxRate), 2);
+ } else {
+ return round(m(this.linePrice, this.taxRate), 2);
+ }
+ }
+
+ get retailPrice() {
+ if (typeof this.retail == "number") {
+ return this.retail;
+ }
+ return this.priceEach * this.qty;
+ }
+
+ set retailPrice(price) {
+ this.retail = num(price);
+ }
+
+}
+export class ReceiptPayment {
+
+ /**
+ *
+ * @param {number} amount amount paid
+ * @param {string} type payment type
+ * @param {string} text extra data (credit card info, etc)
+ * @returns {ReceiptPayment}
+ */
+ constructor(amount, type, text) {
+ this.id = (Math.random() * 100000000) + "_" + type + "_" + amount;
+ this.text = (typeof text != "string" ? "" : text);
+ this.type = type;
+ this.amount = amount;
+ }
+
+ static fromJSON(obj) {
+ var item = new ReceiptPayment(obj.amount, obj.type, obj.text);
+ item.id = obj.id;
+ return item;
+ }
+
+ toJSON() {
+ return {
+ amount: round(this.amount, 2),
+ type: this.type,
+ text: this.text,
+ id: this.id
+ };
+ }
+
+ get texthtml() {
+ if (typeof this.text != "string") {
+ return "";
+ }
+ return this.text.replaceAll("\n", "<br />");
+ }
+
+ get amountFormatted() {
+ return getCurrencySymbol() + this.amount.toFixed(2);
+ }
+
+ get label() {
+ if (typeof this.type != "string") {
+ return "Payment";
+ }
+ switch (this.type) {
+ case "cash":
+ return "Cash";
+ case "check":
+ return "Check";
+ case "card":
+ return "Card";
+ case "card_manual":
+ return "Card";
+ case "account":
+ return "Account";
+ case "free":
+ return "Free";
+ case "discount":
+ return "Discount";
+ case "crypto":
+ return "Cryptocurrency";
+ case "ach":
+ return "ACH Debit";
+ case "rounding":
+ return "Cash Rounding"; // Used in penniless countries to balance a cash-only transaction
+ default:
+ return this.type;
+ }
+ }
+}
+PostalPoint abstracts the receipt printer hardware commands, so the same functions are available on +all brands and languages of receipt printer, and printer media size and settings are also handled for you.
+The drivers operate in line mode, where each successive command appends content to the bottom of the page.
+These functions are available on the object supplied by the promise returned from
+global.apis.print.getReceiptPrinter().
//
+// Add one or more lines of text, with automatic wrapping.
+// If both firsttext and secondtext are provided, two columns of text are generated,
+// with the first left-justified and the second right-justified.
+// `firstjustify` can be "L" (left), "C" (center), or "R" (right).
+// Not all printers support all the formatting options, and may render them in different ways,
+// but the formatting intent is made clear regardless.
+addFieldBlock(firsttext, firstjustify, secondtext = "", secondjustify = "R", bold = false, doubleheight = false, underline = false);
+
+// Add a blank line to the label.
+newLine();
+
+// Draw a horizontal line across the page.
+drawLine();
+
+// Render a Code 128 barcode, centered horizontally, with a human-readable label beneath.
+// Important: this function is sometimes asynchronous depending on the printer driver.
+barcode128(content);
+
+// Print an image. Width is in pixels.
+// pixelByteArray is a Uint8Array where each bit is a pixel (1=black, 0=white),
+// starting at the top-left of the image and going across and then down. Use `imageToBitmap` to
+// obtain this data from a Jimp image.
+// Use "L" as the position to print on the next line, centered horizontally.
+// Some printers also support position = "C", which will
+// ignore other commands and print the image centered on the label,
+// but if you're doing that, just use `global.apis.print.printLabelImage()` instead.
+drawImage(width, position, pixelByteArray);
+
+// If supported by the printer, opens an attached cash drawer. Command is ignored if unavailable.
+openCashDrawer();
+
+// The last command to run, when ready to print. Returns the raw data to send to the printer.
+// Important: this function is sometimes asynchronous depending on the printer driver.
+getData();
+For your reference, here is the source code of the TrackingBarcode class, used to represent a prepaid drop-off.
+This class is provided to plugins as global.apis.barcode.TrackingBarcode.
export class TrackingBarcode {
+ /**
+ * Create a tracking barcode object.
+ * @param {string} code Tracking number.
+ * @returns {TrackingBarcode}
+ */
+ constructor(code) {
+ // All data are optional except for the tracking number. Missing data is gracefully handled by the PostalPoint UI.
+ this.cleanCode = code;
+ // Original barcode data this was created from
+ this.barcode = code;
+ // Destination ZIP Code, for domestic shipments. The city and state are automatically added. If toAddress is specified, toZip is ignored in favor of it.
+ this.toZip = "";
+ // Two-letter destination country code. If not "US", toZip is ignored, and the full country name is appended to the displayed address information.
+ this.toCountry = defaultCountryCode();
+ // If toAddress is set, it will be used instead of the toZip when displaying the destination.
+ // If both toZip and toAddress are empty strings, no destination will be displayed.
+ this.toAddress = "";
+ // If message is not empty, the barcode will NOT be added and the message will be displayed to the user.
+ this.message = "";
+ // If warning is not empty, the barcode WILL be added and a message will be displayed to the user.
+ this.warning = "";
+ // Shipping carrier name.
+ this.carrier = "";
+ // Shipping service/mail class full name and description. Example: "Priority Mail Adult Signature Required".
+ this.serviceName = "";
+ // Shipping service/mail class name, without extra info such as "signature required".
+ // Example: "Priority Mail"
+ this.serviceShort = "";
+ // If set to false, the barcode will be rejected with a suitable message when PostalPoint is running in self-serve kiosk mode.
+ this.dropoff = true;
+ // If false, app may prompt user to specify the shipping carrier
+ this.confidentCarrier = true;
+ // Extra description strings, like "Signature Required"
+ this.extraInfo = [];
+ }
+
+ /**
+ * Set the tracking number
+ * @param {string} str
+ * @returns {undefined}
+ */
+ set tracking(str) {
+ this.cleanCode = str;
+ }
+
+ /**
+ * Set the service/mail class description string.
+ * @param {string} str
+ * @returns {undefined}
+ */
+ set service(str) {
+ this.serviceShort = str;
+ this.serviceName = str;
+ }
+
+ /**
+ * Get the tracking number.
+ * @returns {String}
+ */
+ get tracking() {
+ return this.cleanCode;
+ }
+
+ /**
+ * Get the destination ZIP code.
+ * @returns {String}
+ */
+ get zip() {
+ return this.toZip;
+ }
+
+ /**
+ * Get the service/mail class description.
+ * @returns {String}
+ */
+ get service() {
+ if (this.serviceShort != "") {
+ return this.serviceShort;
+ } else if (this.serviceName != "") {
+ return this.serviceName;
+ }
+ return "";
+ }
+
+ /**
+ * Get the carrier and service info.
+ * @returns {String}
+ */
+ get serviceString() {
+ var str = [];
+ if (this.carrier != "") {
+ str.push(this.carrier);
+ }
+ if (this.serviceShort != "") {
+ str.push(this.serviceShort);
+ } else if (this.serviceName != "") {
+ str.push(this.serviceName);
+ }
+ return str.join(" ");
+ }
+
+ /**
+ * Get the destination information as a human-presentable multiline string.
+ * @returns {String}
+ */
+ get destString() {
+ var addressLines = [];
+ if (this.toAddress != "") {
+ addressLines.push(...this.toAddress.split("\n"));
+ }
+ if (defaultCountryCode() == this.toCountry.toUpperCase() && this.toCountry.toUpperCase() == "US" && this.toZip != "" && this.toAddress == "") {
+ // Domestic shipment within USA, look up ZIP code
+ var zipdata = getZIP(this.toZip);
+ if (zipdata != false) {
+ addressLines.push(`${zipdata.city} ${zipdata.state} ${this.toZip}`);
+ } else {
+ addressLines.push(`${this.toZip}`);
+ }
+ } else if (defaultCountryCode() == this.toCountry.toUpperCase()) {
+ // Domestic shipment, outside USA, add postal code line if we have one
+ if (this.toZip != "" && this.toAddress.includes(this.toZip) != true) {
+ addressLines.push(`${this.toZip}`);
+ }
+ } else {
+ // International shipment, add country name
+ addressLines.push(getCountryNameForISO(this.toCountry));
+ }
+ return addressLines.join("\n");
+ }
+
+ /**
+ * Get the package information in a format suitable for display on a receipt.
+ * @param {boolean} includeTrackingNumber If false, the tracking number will be suppressed.
+ * @returns {String}
+ */
+ toString(includeTrackingNumber = true) {
+ var lines = [];
+ if (includeTrackingNumber && this.cleanCode) {
+ lines.push(this.cleanCode);
+ }
+ var serv = this.serviceString;
+ if (serv != "") {
+ lines.push(serv);
+ }
+ var dest = this.destString;
+ if (dest != "") {
+ var destlines = dest.split("\n");
+ destlines[0] = "To " + destlines[0];
+ lines.push(...destlines);
+ }
+
+ if (typeof this.extraInfo == "object" && this.extraInfo.length > 0) {
+ lines.push(...this.extraInfo);
+ }
+
+ return lines.join("\n");
+ }
+}
+This sample plugin showcases some of the features many plugins will want to use.
+ +// Sample plugin to demonstrate plugin capabilities and structure.
+
+async function getPage() {
+ // A Framework7 component page
+ return global.apis.getPluginFolder("basic-demo") + "/uipluginpage.f7";
+}
+
+// This is run when PostalPoint loads the plugin at launch.
+// Use it to register for things you want to do, like adding a page, hooking into payments or shipping rates, etc.
+exports.init = function () {
+ console.log(global.apis.settings.get("basic-demo_secretcode"));
+ global.apis.ui.addToolsPage(getPage, "Sample Page Title", "sampletool1234", "A sample plugin page", "Sample", "fa-solid fa-circle");
+};
+
+// This defines a settings UI to display for the plugin.
+// If exports.config is a function instead of an array, it will be executed when opening the settings
+// and must return an array like the one below.
+// If exports.config is undefined, a settings menu will not be provided to the user.
+exports.config = [
+ {
+ type: "button",
+ label: "Test Button",
+ text: "Some text about the button",
+ onClick: function () {
+ global.apis.alert("Button pressed");
+ }
+ },
+ {
+ type: "text",
+ key: "app.postalpoint.basic-demo_somestring", // Try to make sure this is unique by using a prefix,
+ // settings storage is global so there could be conflicts if you aren't careful
+ defaultVal: "",
+ label: "Type a string",
+ placeholder: "",
+ text: "Description text next to the input box",
+ sync: false // Add sync: false to prevent automatically syncing this setting between
+ // PostalPoint installations (i.e. it's a device-specific setting, like a pairing code)
+ // If it's not present, or is any truthy value, it could be synced between PCs
+ },
+ {
+ type: "password",
+ key: "app.postalpoint.basic-demo_secretcode",
+ defaultVal: "",
+ label: "Secret Code",
+ placeholder: "",
+ text: "Don't tell anyone this secret code:"
+ },
+ {
+ type: "textarea",
+ key: "app.postalpoint.basic-demo_sometext",
+ defaultVal: "",
+ label: "Text Box",
+ placeholder: "...",
+ text: "You can type a few lines of text here."
+ },
+ {
+ type: "select",
+ key: "app.postalpoint.basic-demo_dropdownbox",
+ defaultVal: "",
+ label: "Choose an option",
+ placeholder: "",
+ text: "",
+ options: [["key1", "Value 1"], ["key2", "Value 2"]]
+ }
+];
+<template>
+ <div class="page">
+ <div class="navbar">
+ <div class="navbar-bg"></div>
+ <div class="navbar-inner">
+ <div class="title">${title}</div>
+ </div>
+ </div>
+ <div class="page-content">
+ <a class="button" @click=${openAlert}>Open Alert</a>
+ <a class="button" @click=${printSomething}>Print Something</a>
+ <div class="list simple-list">
+ <ul>
+ ${names.map((name) => $h`
+ <li>${name}</li>
+ `)}
+ </ul>
+ </div>
+ </div>
+ </div>
+</template>
+<!-- component styles -->
+<style>
+ .red-link {
+ color: red;
+ }
+</style>
+<!-- rest of component logic -->
+<script>
+ // script must return/export component function
+ export default (props, { $f7, $on }) => {
+ const title = 'Component Page';
+ const names = ['John', 'Vladimir', 'Timo'];
+
+ const openAlert = () => {
+ $f7.dialog.alert('Hello world!\nblah blah blah');
+ }
+
+ async function printSomething() {
+ // Print some text to the receipt printer
+ var printer = await global.apis.print.getReceiptPrinter();
+ printer.addFieldBlock('Hello world!\nblah blah blah\n\n', "C");
+ global.apis.print.printReceiptData(await printer.getData());
+ }
+
+ $on('pageInit', () => {
+ // do something on page init
+ });
+ $on('pageAfterOut', () => {
+ // page has left the view
+ });
+
+ // component function must return render function
+ return $render;
+ }
+</script>
+This sample plugin demonstrates how to add support for a custom shipping carrier.
+ +// This is a sample PostalPoint plugin for adding support for a shipping carrier.
+
+var rateCache = [];
+var parcelCache = {};
+
+exports.init = function () {
+ // Add support for shipping rating and label purchasing
+ global.apis.shipping.registerRateEndpoint(getRates, purchase, "uniqueprefixhere_");
+
+ // Add support for prepaid drop-offs
+ global.apis.barcode.onPrepaidScan(function (barcode) {
+ if (barcode.startsWith("mycarrierbarcode")) { // Replace this with your checks for barcode validity
+ var data = new global.apis.barcode.TrackingBarcode(barcode);
+ data.carrier = "Carrier Name";
+ data.service = "Service Name";
+ return data;
+ }
+ return false;
+ });
+}
+
+async function purchase(rateid) {
+ for (var i = 0; i < rateCache.length; i++) {
+ if (rateCache[i].rateid == rateid) {
+ var rate = rateCache[i];
+ //
+ // Fetch label and tracking and such
+ //
+ var label;
+ var tracking = "123456";
+ var toAddressLines = parcelCache.toAddress.toStringArray();
+
+ // Create receipt item
+ var receiptitem = new global.apis.pos.ReceiptItem(`uniqueprefixhere_${tracking}`,
+ `${rate.carrierName} ${rate.serviceName}`,
+ `Tracking # ${global.apis.util.string.chunk(tracking, 3).join(" ")}\nTo:\n${toAddressLines.join("\n")}`,
+ rate.retail_rate, 1, rate.cost_rate, 0
+ );
+ receiptitem.barcode = tracking;
+ receiptitem.carrier = "Carrier Name";
+ receiptitem.service = "Service Name";
+
+ return {
+ label: label,
+ labeltype: "PNG",
+ receiptItem: receiptitem,
+ tracking: tracking,
+ cost: rate.cost_rate,
+ price: rate.retail_rate,
+ carrier: rate.carrierName,
+ service: rate.serviceName,
+ delivery_days: rate.delivery_days,
+ delivery_date: rate.delivery_date,
+ to: toAddressLines
+ };
+ }
+ }
+}
+
+async function getRates(parcel) {
+ // parcel is an object as shown in docs/Parcel.md
+ var rates = [];
+ rates.push({
+ rateid: "uniqueprefixhere_" + global.apis.util.uuid.v4(),
+ carrier: "Carrier",
+ carrierName: "Carrier Name",
+ service: "CARRIER_SERVICE_ID",
+ cost_rate: 10,
+ retail_rate: 15,
+ delivery_days: 3,
+ delivery_date: null,
+ guaranteed: true,
+ serviceName: "Service Name",
+ color: "green" // Rate card color
+ });
+
+ // Save details for later use if purchased
+ rateCache = rates;
+ parcelCache = parcel;
+
+ return rates;
+}
+This plugin template shows how to implement a card payment processor, +allowing PostalPoint to interface with your card reader/terminal hardware, +as well as saving, retrieving, and charging cards on file.
+ +// This is a sample PostalPoint plugin that adds a card payment processor.
+
+exports.init = function () {
+ global.apis.pos.registerCardProcessor({
+ name: "Demo Card Processor",
+ init: async function () {
+ // This function runs once after starting PostalPoint
+ // and before any other card processor functions are called.
+ },
+ checkout: async function({amount, capture = true}) {
+ // amount is an integer number of pennies.
+
+ // If an error is encountered during processing,
+ // display an error message in a dialog and return boolean false.
+ // If this function returns anything except false or undefined, and doesn't throw an error,
+ // it is assumed the payment was successful.
+ try {
+ if (capture) {
+ // authorize, capture, add a ReceiptPayment to the receipt, and return boolean true.
+ global.apis.pos.addOnscreenPaymentLog("Getting card payment..."); // Add a line to the onscreen card processing status log
+ await global.apis.util.delay(1000); // Replace this with something useful!
+ global.apis.pos.addReceiptPayment(
+ new global.apis.pos.ReceiptPayment(
+ (amount / 100).toFixed(2) * 1,
+ "card", // Payment type. Accepted values are card, ach, crypto, cash, check, account, and free. Other types will be displayed as-is to the user and on the receipt.
+ "Demo Card\nCardholder Name, etc\nMore info for receipt" // Additional text for receipt
+ )
+ );
+ global.apis.pos.addOnscreenPaymentLog("Payment successful!");
+ return true;
+ } else {
+ // only authorize the payment, don't actually capture/charge the payment method,
+ // and return whatever transaction data that will be passed to finishPayment to capture the payment.
+ await global.apis.util.delay(1000); // Replace this with something useful!
+ return {amount: amount};
+ }
+ } catch (ex) {
+ global.apis.pos.addOnscreenPaymentLog(`Error: ${ex.message} [okay to put extra details here for troubleshooting or tech support, it's visible to the cashier]`);
+ if (global.apis.kiosk.isKiosk()) {
+ // This message will be shown to an end-user/customer, not a cashier/employee
+ global.apis.alert("Your card was declined.", "Card Error");
+ } else {
+ global.apis.alert("The customer's card was declined.", "Card Error");
+ }
+ return false;
+ }
+ },
+ cancelCheckout: function () {
+ // The user requested to cancel the payment.
+ // Reset the terminal to its resting state, clear its screen, etc.
+ },
+ finishPayment: async function ({checkoutResponse}) {
+ // Finish a payment that was authorized but not captured because checkout was called with capture = false
+ // If payment was already captured and added to the receipt for some reason, just return true.
+ await global.apis.util.delay(1000); // Replace this with something useful!
+ global.apis.pos.addReceiptPayment(
+ new global.apis.pos.ReceiptPayment(
+ (checkoutResponse.amount / 100).toFixed(2) * 1,
+ "card", // Payment type.
+ "Demo Card\nCardholder Name, etc\nMore info for receipt" // Additional text for receipt
+ )
+ );
+ return true;
+ },
+ updateCartDisplay: function (receipt) {
+ // Show transaction data on the card reader display.
+ // This function will be called when the cart or total changes.
+ console.log(receipt);
+ // Sample structure of the receipt variable:
+ receipt = {
+ "items": [
+ {
+ "id": "testitem",
+ "label": "Test Item",
+ "text": "",
+ "priceEach": 2,
+ "qty": 1,
+ "cost": 0,
+ "retail": 2,
+ "taxRate": 0.1,
+ "free": false,
+ "barcode": "",
+ "certifiedInfo": false,
+ "isMerch": true,
+ "surcharge": false
+ },
+ {
+ "id": "9100123456789012345678",
+ "label": "Test Package",
+ "text": "Package Details\nTracking # 9100 1234 5678 9012 3456 78\nTo:\nTEST PERSON\nORGANIZATION INC\n123 TEST ROAD\nTESTTOWN TE 99999-0001",
+ "priceEach": 8,
+ "qty": 1,
+ "cost": 0,
+ "retail": 8,
+ "taxRate": 0,
+ "free": false,
+ "barcode": "9100123456789012345678",
+ "certifiedInfo": false,
+ "isMerch": false,
+ "surcharge": false,
+ "toAddress": {
+ "name": "TEST PERSON",
+ "company": "ORGANIZATION INC",
+ "street1": "123 TEST ROAD",
+ "street2": null,
+ "city": "TESTTOWN",
+ "state": "TE",
+ "zip": "99999-0001",
+ "email": null,
+ "phone": null,
+ "country": "US"
+ },
+ "fromAddress": {
+ "name": "TEST PERSON",
+ "company": "ORGANIZATION INC",
+ "street1": "123 TEST ROAD",
+ "street2": null,
+ "city": "TESTTOWN",
+ "state": "TE",
+ "zip": "99999-0001",
+ "email": null,
+ "phone": null,
+ "country": "US"
+ }
+ }
+ ],
+ "payments": [
+ {
+ "amount": 10,
+ "amountFormatted": "$10.00",
+ "type": "cash",
+ "label": "Cash",
+ "text": "",
+ "texthtml": "",
+ "id": "12345678_cash_10"
+ },
+ {
+ "amount": 12.34,
+ "amountFormatted": "$12.34",
+ "type": "card",
+ "label": "Card",
+ "text": "Card Details here\n1234abcd",
+ "texthtml": "Card Details here<br />1234abcd",
+ "id": "87654321_card_12.34"
+ }
+ ],
+ "subtotal": 10,
+ "subtotalFormatted": "$10.00",
+ "tax": 0.2,
+ "taxFormatted": "$0.20",
+ "grandTotal": 10.2,
+ "grandTotalFormatted": "$10.20",
+ "paid": 22.34,
+ "paidFormatted": "$22.34",
+ "due": -12.14, // If negative, is the amount of change owed to the customer instead
+ "dueFormatted": "$12.14"
+ };
+ },
+ checkoutSavedMethod: async function ({customerID, paymentMethodID, amount}) {
+ // Same as checkout() except using a payment method already on file.
+ // customerID and paymentMethodID are provided by getSavedPaymentMethods below.
+ await global.apis.util.delay(1000); // Replace this with something useful!
+ var error = false;
+ if (error) {
+ // If you can't charge the payment method, throw an Error with a string to display to the user.
+ throw new Error("The saved card didn't work.");
+ }
+ global.apis.pos.addReceiptPayment(
+ new global.apis.pos.ReceiptPayment(
+ (amount / 100).toFixed(2) * 1,
+ "card", // Payment type.
+ "Card on File\nx1234" // Additional text for receipt
+ )
+ );
+ // Must return true upon success.
+ // If the payment is not successful, and you didn't throw an Error to show the user,
+ // then `return false` instead and it'll appear that the user's action to start the payment did nothing.
+ return true;
+ },
+ saveCardForOfflineUse: async function ({statusCallback, customerUUID, name, company, street1, street2, city, state, zip, country, email, phone}) {
+ // Use the card reader to capture an in-person card and save it for offline use.
+ // Provided details are the customer's info, which might be empty strings except for the customerUUID.
+ // Saved card details must be tied to the customerUUID, as that's how saved cards are looked up.
+
+ // statusCallback(string, boolean) updates the progress message on the cashier's screen.
+ // If the boolean is true, the progress message is replaced with a confirmation message.
+ statusCallback("Insert the card into the reader.", false);
+
+ await global.apis.util.delay(1000); // Wait for the customer to insert their card,
+ //then save it for later offline billing
+
+ statusCallback("Saving card details...", false);
+
+ await global.apis.util.delay(1000);
+
+ statusCallback("Card saved!", true);
+
+ return true; // Card saved to customer
+ // If an error occurred, you can throw it and the error message will be displayed to the cashier.
+ // Alternatively, return boolean false and display the error yourself with global.apis.alert(message, title) or something.
+ },
+ cancelSaveCardForOfflineUse: function () {
+ // Cancel the process running in saveCardForOfflineUse() at the user/cashier's request.
+ },
+ getSavedPaymentMethods: async function ({customerUUID}) {
+ // Return all saved payment methods tied to the provided customer UUID.
+ var methods = [];
+ methods.push({
+ customer: "<internal string referencing the customer>", // Passed to checkoutSavedMethod as customerID
+ customer_uuid: customerUUID,
+ id: "<card/payment method identifier>", // Passed to checkoutSavedMethod as paymentMethodID
+ type: "card", // Payment type. Accepted values are card, ach, crypto, cash, check, account, and free.
+ label: "Visa debit x1234 (exp. 12/29)", // Label for payment method
+ label_short: "Visa debit x1234" // Abbreviated label for payment method
+ });
+ return methods;
+ },
+ deleteSavedPaymentMethod: async function ({customerUUID, customerID, paymentMethodID}) {
+ // Delete the payment method identified by paymentMethodID and tied to the PostalPoint customerUUID and the card processor customerID.
+ // If unable to delete, throw an error and the error message will be displayed to the cashier.
+ await global.apis.util.delay(1000);
+ }
+ });
+}
+
+// Plugin settings to display.
+exports.config = [
+ {
+ type: "password",
+ key: "democardprocessor_apikey",
+ defaultVal: "",
+ label: "API Key",
+ placeholder: "",
+ text: "API Key"
+ },
+ {
+ type: "button",
+ label: "Test Button",
+ text: "Some text about the button",
+ onClick: function () {
+ global.apis.ui.openSystemWebBrowser("https://postalpoint.app");
+ }
+ }
+];
+This plugin template shows how to implement a cryptocurrency payment processor, +using the customer-facing display to show a payment QR code webpage.
+ +// This is a sample PostalPoint plugin that adds a card payment processor.
+
+exports.init = function () {
+ global.apis.pos.registerCryptoProcessor({
+ name: "Demo Crypto",
+ init: async function () {
+ // This is run after PostalPoint starts, and before any other crypto functions are called.
+ },
+ checkout: async function ( {amount}) {
+ // Run the checkout process.
+ // amount is the amount of USD to collect, in pennies.
+
+ // If an error is encountered during processing,
+ // display an error message in a dialog and return boolean false.
+ // If this function returns anything except false or undefined, and doesn't throw an error,
+ // it is assumed the payment was successful.
+
+ // Adds a line of text visible to the cashier
+ global.apis.pos.addOnscreenPaymentLog("Getting crypto payment...");
+
+ // Display a web page (i.e. with a payment QR code) to the customer on the customer-facing display.
+ global.apis.ui.setCustomerScreen("<html></html>", "html");
+ global.apis.ui.setCustomerScreen("https://postalpoint.app", "raw");
+
+ // Poll the status of the crypto transaction
+ var paymentComplete = false;
+ do {
+ await global.apis.util.delay(1000);
+ paymentComplete = true;
+ } while (paymentComplete != true);
+
+ global.apis.pos.addReceiptPayment(
+ new global.apis.pos.ReceiptPayment(
+ (amount / 100).toFixed(2) * 1,
+ "crypto", // Payment type.
+ "Bitcoin\n0.00001234 BTC" // Additional text for receipt
+ )
+ );
+ global.apis.pos.addOnscreenPaymentLog("Payment successful!");
+ global.apis.ui.clearCustomerScreen();
+ },
+ cancelCheckout: function () {
+ // The user requested to cancel the payment.
+ // Reset things accordingly.
+ global.apis.ui.clearCustomerScreen();
+ },
+ isConfigured: function () {
+ // Is this plugin properly setup and able to process payments? If not, return false.
+ return true;
+ }
+ });
+}
+
+// Plugin settings to display.
+exports.config = [
+ {
+ type: "password",
+ key: "democryproprocessor_apikey",
+ defaultVal: "",
+ label: "API Key",
+ placeholder: "",
+ text: "API Key"
+ },
+ {
+ type: "button",
+ label: "Test Button",
+ text: "Some text about the button",
+ onClick: function () {
+ global.apis.ui.openSystemWebBrowser("https://postalpoint.app");
+ }
+ }
+];
+objectHandle tracking barcodes
+Kind: global namespace
+object
+Kind: static class of barcode
+Properties
| Name | +Type | +Description | +
|---|---|---|
| tracking | +string |
+Tracking number | +
| barcode | +string |
+Original barcode data this was created from | +
| toZip | +string |
+Destination ZIP Code, for domestic shipments. The city and state are automatically added. If toAddress is specified, toZip is ignored in favor of it. | +
| toCountry | +string |
+Two-letter destination country code. If it doesn't match the country PostalPoint is running in, the full country name is appended to the displayed address information. | +
| toAddress | +string |
+Destination mailing/shipping address. | +
| carrier | +string |
+Shipping carrier name. | +
| service | +string |
+Shipping service/mail class name. Example: "Priority Mail". | +
| dropoff | +boolean |
+If set to false, the barcode will be rejected with a suitable message when PostalPoint is running in self-serve kiosk mode. | +
| confidentCarrier | +boolean |
+If false, PostalPoint may prompt user to specify the shipping carrier. | +
| extraInfo | +Array.<string> |
+Extra description strings, like "Signature Required". | +
| message | +string |
+If not empty, the barcode will NOT be added and the contents of message will be displayed to the user. |
+
| warning | +string |
+If not empty, the barcode WILL be added and the contents of warning will be displayed to the user. |
+
| destString | +string |
+(read only) Get the destination information as a human-presentable multiline string. | +
| serviceString | +string |
+(read only) Get the carrier and service. | +
| toString() | +function |
+Get the package information in a format suitable for display on a receipt. | +
| toString(false) | +function |
+Get the package information in a format suitable for display on a receipt, suppressing the tracking number. | +
A Tracking barcode object.
+| Param | +Type | +Description | +
|---|---|---|
| code | +string |
+Barcode data | +
Add a TrackingBarcode object to the transaction receipt at any time other than onPrepaidScan.
Kind: static method of barcode
| Param | +Type | +
|---|---|
| trackingBarcodeData | +TrackingBarcode |
+
Pass data to the internal barcode event subsystem. The data is handled as if it +were just received from a physical barcode scanner.
+Kind: static method of barcode
| Param | +Type | +
|---|---|
| barcodeData | +string |
+
The function passed to onPrepaidScan is run when a barcode is scanned on the Prepaid page. +The function is passed one argument, a string containing the raw barcode data. +The function shall return boolean false if unable or unwilling to handle the barcode. +If the barcode is handled by this function, it shall return a TrackingBarcode object.
+Kind: static method of barcode
| Param | +Type | +
|---|---|
| f | +function |
+
objectDatabase connection
+ +Promise.<DatabaseAdapter>Return a database connection object to run SQL against the store database. See the Database docs for details.
+Kind: static method of database
objectBasic filesystem access utility functions, wrapping Node.JS and/or NW.JS code.
+Kind: global namespace
+objectPromise.<(string|null)>string | nullPromisePromise.<(string|Buffer)>booleanPromise.<(string|null)>Open a file save as dialog prompting the user to save a file. +Opens to the user's Documents folder, with sane fallbacks if it cannot be located.
+Kind: static method of fs
+Returns: Promise.<(string|null)> - The full file path the user selected, or null if they cancelled.
| Param | +Type | +Description | +
|---|---|---|
| suggestedFilename | +string |
+The filename string to pre-fill in the dialog. | +
| fileExtensions | +string |
+The file type filter to show. Examples: ".csv", ".csv,.html" | +
string | nullOpen a file browse/file open dialog prompting the user to select a file or folder. +Opens to the user's Documents folder, with sane fallbacks if it cannot be located.
+Kind: static method of fs
+Returns: string | null - The selected file/folder path, or null if cancelled.
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| chooseFolder | +boolean |
+false |
+Set to true to choose a folder instead of a file. | +
| accept | +string |
++ | File filter. ".csv,.html", "image/*", etc. | +
| dialogTitle | +string | null |
+null |
+Title of the file open dialog. | +
PromiseWrite a file to disk.
+Kind: static method of fs
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| filename | +string |
++ | The path and filename to write to. | +
| data | +string | Buffer | ArrayBuffer | Uint8Array |
++ | Data to write to the file. | +
| encoding | +string | null |
+"utf8" |
+Text encoding. Set to empty if not passing string data. | +
| flag | +string | null |
+"w+" |
+Filesystem flag. | +
Promise.<(string|Buffer)>Read a file from disk and return its contents.
+Kind: static method of fs
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| filename | +string |
++ | The path and filename to read from. | +
| encoding | +string |
+"utf8" |
+File encoding. Set to null or empty string when reading binary data. | +
| flag | +string |
+"r+" |
+Filesystem flag. | +
booleanCheck if a file exists.
+Kind: static method of fs
| Param | +Type | +Description | +
|---|---|---|
| filename | +string |
+Path and filename to check. | +
The Framework7 app instance for PostalPoint's entire UI, created by new Framework7(). +See https://framework7.io/docs/app for details.
+ +stringGet the filesystem path to a plugin's installation folder.
+Kind: global function
+Returns: string - "/home/user/.config/postalpoint-retail/Default/storage/plugins/...", "C:\Users\user\AppData...", etc
| Param | +Type | +Description | +
|---|---|---|
| [id] | +string |
+Plugin ID. If omitted or empty, will return the parent folder plugins are installed within. | +
stringGet the filesystem path to the PostalPoint installation folder.
+ +Display a simple alert-style dialog box.
+Kind: global function
+| Param | +Type | +Default | +Description | +
|---|---|---|---|
| text | +string |
++ | Body text of the dialog. | +
| title | +string |
++ | Dialog title. | +
| [callback] | +function |
+ |
+Function to call when the alert is closed. | +
objectPostalPoint uses the Jimp library version 1.6 for creating and manipulating images and shipping labels.
+Kind: global namespace
+objectJimpPromiseJimpThe JavaScript Image Manipulation Program.
+Kind: static method of graphics
+Example
+
PromiseReplacement for Jimp's loadFont function, +which gets very confused about our JS environment and ends up crashing everything.
+Kind: static method of graphics
| Param | +Type | +
|---|---|
| filename | +string |
+
objectFunctions to help support multiple currencies and countries.
+Kind: global namespace
+objectstringstringstringnumberPromise.<number>stringstringnumbernumberstringGet the 2-character ISO country code that PostalPoint is running in.
+Kind: static method of i18n
+Returns: string - "US", "CA", etc.
+
stringGet the 3-character currency code in use.
+Kind: static method of i18n
+Returns: string - "usd", "cad", etc.
+
stringGet the currency symbol.
+Kind: static method of i18n
+Returns: string - "$", "€", "₤", etc
+
numberGet the number of decimal places for the currency: for example, USD has 2 ($x.00), KRW has 0 (x), UYW has 4 (x.0000).
+Kind: static method of i18n
+Returns: number - 0, 2, 3, or 4
+
Promise.<number>Convert an amount of money to a different currency. Conversion rate is retrieved from the internet and cached for 4 hours.
+Kind: static method of i18n
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| amount | +number |
++ | Amount of money in the "wrong" currency | +
| fromCurrency | +string |
++ | The currency code for the "wrong" currency that needs conversion | +
| [toCurrency] | +string |
+"getCurrencyCode()" |
+The "correct" currency we want the amount to be in. | +
stringReturns the amount as a string formatted with the correct number of decimal places for the currency in use.
+Kind: static method of i18n
+Returns: string - "1.23", "1.2345", etc
| Param | +Type | +
|---|---|
| amount | +number |
+
stringReturns the amount as a string, with the correct decimal places, and the local currency symbol.
+Kind: static method of i18n
+Returns: string - "$1.23", etc
| Param | +Type | +
|---|---|
| amount | +number |
+
numberConvert an amount in cents to dollars (or the local equivalent currency units).
+Kind: static method of i18n
+Returns: number - Dollars, etc
| Param | +Type | +Description | +
|---|---|---|
| amount | +number |
+Cents, etc | +
numberConvert an amount in dollars to cents (or the local equivalent currency units).
+Kind: static method of i18n
+Returns: number - Cents, etc
| Param | +Type | +Description | +
|---|---|---|
| amount | +number |
+Dollars, etc | +
objectSelf-serve kiosk mode
+ +booleanCheck if PostalPoint is running in kiosk mode.
+Kind: static method of kiosk
+Returns: boolean - - True if system is in kiosk mode, else false.
objectAdd, modify, and delete mailboxes and mailbox customers.
+Kind: global namespace
+objectPromise.<Array>PromisePromisePromisePromisePromisePromisePromise.<boolean>PromisePromisePromise.<FormPS1583>PromisebooleanPromise.<Array>Kind: static class of mailboxes
+
USPS Form PS1583 object, with all the fields needed by USPS for CMRA customers.
+ +Promise.<Array>Get the list of mailboxes and boxholders as an array of objects, see example.
+Kind: static method of mailboxes
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| filter | +null | object |
+ |
+Filter to mailboxes matching a column condition, such as getList({number: "102"}) or getList({"size >=": "2"}). Supported filter names include "number" (string, box number), "expires" (expiration date), "size" (number 1-10), and "barcode" (string) SQL injection warning: Filter names are inserted directly into query strings without sanitization. Only the values are safe for user input. |
+
Example
+
[{
+ num: "123", // Box number as string
+ expires: 1234567890, // UNIX timestamp (in seconds) or false if box vacant
+ size: "2", // Box size, 1-10
+ notes: "", // Notes for mailbox, not currently shown in Mailbox Manager UI but may be used in the future
+ barcode: "", // Unique barcode for the mailbox, for future use
+ renewalMerchID: "", // Merchandise item ID used for autorenewing this mailbox
+ isBusiness: false, // True if the box is for a business, false if for personal use
+ names: [], // Array of boxholders. See addOrUpdateBoxholder for the format.
+ packages: [], // Array of packages awaiting pickup, see below
+ vacant: false // True if the box is currently vacant, else false
+}]
+// Data objects in the packages array:
+{
+ tracking: tracking ?? "[Untracked]", // Package tracking number
+ finalized: true, // True if package check-in is finished and shelf tag/mailbox slips printed, false if not finalized
+ available_date: Date(), // The date and time the package was checked in
+ tag: "" // Unique number assigned to the package and printed on shelf tags, scanned by employee when customer picks up package
+}
+PromiseAdd a number of days or months to a mailbox's expiration. Use either days or months, not both.
+Kind: static method of mailboxes
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| boxNumber | +string |
++ | Mailbox number. | +
| days | +number |
+0 |
+Days to add. | +
| months | +number |
+0 |
+Months to add. | +
PromiseSet the box expiration to a specific JavaScript Date object, or a UNIX timestamp (in seconds).
+Kind: static method of mailboxes
| Param | +Type | +
|---|---|
| boxNumber | +string |
+
| date | +number | Date |
+
PromiseCreate a new mailbox number with the specified box size. Throws an error if the box number is already in use.
+Kind: static method of mailboxes
| Param | +Type | +Description | +
|---|---|---|
| number | +string |
+Mailbox number | +
| size | +number |
+Box size (1 - 10) | +
| notes | +string |
+Arbitrary string with human-readable notes about the box. | +
| barcode | +null | string |
+A barcode value representing this mailbox, typically a sticker on the the physical box visible when delivering mail. | +
PromiseChange the number and/or size of a mailbox while preserving the boxholders +and packages associated. If only changing size, set oldNumber and newNumber to the same value.
+Kind: static method of mailboxes
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| oldNumber | +string |
++ | Currently assigned box number. | +
| newNumber | +string |
++ | New box number. Must not exist yet. | +
| newSize | +number | null |
+ |
+Box size (1 - 10), if changing the size. | +
| barcode | +null | string |
++ | A barcode value representing this mailbox, typically a sticker on the the physical box visible when delivering mail. | +
PromiseDelete a mailbox. Throws an Error if the mailbox has boxholders attached.
+Kind: static method of mailboxes
| Param | +Type | +Description | +
|---|---|---|
| number | +string |
+Mailbox number to delete. | +
PromiseClose a mailbox by removing the boxholders and marking it as vacant. +Boxholder PS Form 1583 records are automatically archived per USPS regulations.
+Kind: static method of mailboxes
| Param | +Type | +Description | +
|---|---|---|
| number | +string |
+Mailbox number to close. | +
Promise.<boolean>Returns true if the mailbox number exists, false if it doesn't.
+Kind: static method of mailboxes
| Param | +Type | +Description | +
|---|---|---|
| number | +string |
+Mailbox number to check. | +
PromiseModify or add a boxholder to a mailbox. info is the boxholder structure below. +If the uuid given already belongs to a boxholder, their info is updated with what you supply. +Otherwise, the info is added as a new boxholder.
+Kind: static method of mailboxes
| Param | +Type | +Description | +
|---|---|---|
| boxNumber | +string |
+Mailbox number | +
| info | +Object |
+Boxholder information. | +
Example
+
// Unless noted, all fields are strings and default to an empty string.
+{
+ name: [bizname, fname, mname, lname].filter(Boolean).join(" "),
+ fname: "", // First name
+ mname: "", // Middle name
+ lname: "", // Last name
+ email: "", // Email
+ phone: "", // Phone
+ uuid: "", // Customer UUID
+ bizname: "", // Business name
+ street1: "", // Street address
+ city: "", // City
+ state: "", // Two-character state
+ zipcode: "", // ZIP or postal code
+ country: "", // Two-character country code
+ primary: true // True if the primary (first) boxholder, false if an additional authorized mail recipient
+}
+PromiseRemove a boxholder by their UUID, and archive their PS Form 1583 data per USPS regulations.
+Kind: static method of mailboxes
| Param | +Type | +Description | +
|---|---|---|
| boxNumber | +string |
+Mailbox number. | +
| uuid | +string |
+Boxholder UUID. | +
Promise.<FormPS1583>Get the FormPS1583 object for a boxholder by UUID.
+Kind: static method of mailboxes
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| boxNumber | +string |
++ | Mailbox number. | +
| uuid | +string |
++ | Boxholder UUID. | +
| archiveNumber | +boolean |
+false |
+If true, returns the form for a deleted boxholder from the archive. | +
PromiseSet the FormPS1583 object for a boxholder by UUID.
+Kind: static method of mailboxes
| Param | +Type | +Description | +
|---|---|---|
| boxNumber | +string |
+Mailbox number. | +
| uuid | +string |
+Boxholder UUID. | +
| formps1583 | +FormPS1583 |
+The FormPS1583 object to use. | +
booleanReturns true if the mailbox number is an acceptable format, false if it isn't. +Does not check if the box actually exists, merely if the number is acceptable to use as a mailbox number.
+Kind: static method of mailboxes
+
Promise.<Array>Get a list of merchandise items that are usable for mailbox renewals.
+Kind: static method of mailboxes
+Example
+
[{
+ id: "", // Unique ID for this entry in the merchandise table
+ name: "", // Merch item name
+ category: "", // Merch item category
+ price: 0.0, // Sale price in dollars
+ cost: 0.0, // Merchandise cost in dollars (likely not used for mailboxes)
+ barcode: "", // Barcode/UPC (likely not used for mailboxes)
+ tax: 0.0, // Sales tax rate
+ rentaldays: 30, // Number of days this item adds to a mailbox (mutually exclusive with rentalmonths)
+ rentalmonths: 1, // Number of months (mutually exclusive with rentaldays)
+ boxsize: "1" // Mailbox size tier, 1-10
+}]
+objectPoint of Sale, transaction, and payment-related functionality.
+Kind: global namespace
+object
+Kind: static class of pos
+Properties
| Name | +Type | +Default | +Description | +
|---|---|---|---|
| merch | +boolean |
+false |
+True if merchandise, false if shipping. | +
| barcode | +string |
++ | Item barcode, or tracking number if merch = false. |
+
| qty | +number |
+1 |
+Item quantity. | +
| retailPrice | +number |
++ | The calculated retail/markup price for a shipment, regardless of actual sale price. If unset, defaults to priceEach * qty. | +
| taxRate | +number |
+0 |
+Tax rate | +
| toAddress | +Address |
++ | Shipping destination address. | +
| fromAddress | +Address |
++ | Shipping return address. | +
| carrier | +string |
++ | Shipping carrier. | +
| service | +string |
++ | Shipping service. | +
| category | +string |
++ | Merchandise/item category. | +
| electronicReturnReceipt | +boolean |
+false |
+If true, the customer's receipt will have instructions on retrieveing the return receipt from USPS. | +
| mailboxDays | +number |
+0 |
+Number of days this item adds to a mailbox's expiration date. | +
| mailboxMonths | +number |
+0 |
+Number of months this item adds to a mailbox's expiration date. | +
| mailboxNumber | +string |
++ | Mailbox number to apply mailboxDays or mailboxMonths to after checkout. |
+
| setCertifiedInfo() | +function |
++ | Set Certified Mail receipt data. setCertifiedInfo(trackingNumber, certfee, extrafees, postage, date, location, toaddress) |
+
| toJSON() | +function |
++ | Get the item as an object suitable for JSON encoding. | +
| fromJSON(json) | +static_function |
++ | Returns a ReceiptItem created from the object returned by item.toJSON(). |
+
A class representing a sale item in the current transaction.
+| Param | +Type | +Default | +Description | +
|---|---|---|---|
| id | +string |
++ | Unique ID number for this item (UPC code, inventory number, etc). Used to deduplicate and merge line items on the receipt. Unique items (like shipping labels) should be a unique/random ID. | +
| label | +string |
++ | One-line item information. | +
| text | +string |
++ | Extra multi-line item information. | +
| priceEach | +number |
++ | Sale price per unit. | +
| quantity | +number |
++ | Number of units. | +
| cost | +number |
++ | Cost per unit. Used for automatic expense tracking. | +
| taxrate | +number |
+0.0 |
+Examples: 0 (for 0%), 0.05 (for 5%), etc | +
| taxableAmount | +string |
++ | The part of the sale price that's taxable. "" for default (all), "markup" for only taxing profit. | +
Kind: static class of pos
+Properties
| Name | +Type | +Description | +
|---|---|---|
| label | +string |
+(readonly) The human-readable string of the payment type. | +
| id | +string |
+Automatically-generated unique ID for this payment. | +
| toJSON() | +function |
+Get the payment as an object suitable for JSON encoding. | +
| fromJSON(json) | +static_function |
+Returns a ReceiptPayment created from the object returned by payment.toJSON(). |
+
A class representing a payment entry for the current transaction.
+| Param | +Type | +Description | +
|---|---|---|
| amount | +number |
+amount paid | +
| type | +string |
+payment type | +
| text | +string |
+extra data (credit card info, etc) | +
Add an item (shipment, merchandise, etc) to the current transaction.
+Kind: static method of pos
| Param | +Type | +
|---|---|
| item | +ReceiptItem |
+
Add a payment to the current transaction/receipt.
+Kind: static method of pos
| Param | +Type | +
|---|---|
| payment | +ReceiptPayment |
+
Append a line of text to the onscreen log displayed during credit card processing. +Not shown in kiosk mode.
+Kind: static method of pos
| Param | +Type | +Description | +
|---|---|---|
| msg | +string |
+Line of text to add to the log. | +
stringGet the unique alphanumeric ID for the current transaction/receipt. +This is the same code printed on receipts and used in digital receipt URLs.
+Kind: static method of pos
+
Specify a function to be called whenever the transaction data/receipt is changed. +It is passed a single argument, a Receipt object containing the entire transaction so far.
+Kind: static method of pos
| Param | +Type | +
|---|---|
| f | +function |
+
Deprecated
+The supplied function will be called when a transaction is finished.
+It is passed a single argument, a Receipt object containing the entire transaction.
+Recommended to listen for the transactionFinished event instead.
Kind: static method of pos
| Param | +Type | +
|---|---|
| f | +function |
+
Register as a card payment processor.
+Kind: static method of pos
| Param | +Type | +Description | +
|---|---|---|
| f | +Object |
+Payment processor functions | +
Example
+
global.apis.pos.registerCardProcessor({
+ name: "Demo Card Processor", // Shown in PostalPoint settings menu
+ init: async function () {
+ // This will run after PostalPoint launches
+ // and before any payments are processed.
+ // In some situations it might run multiple times in a session.
+ },
+ checkout: async function ({amount, capture = true}) {
+ // Charge a credit card using a card reader device.
+ // amount is in pennies (or the equivalent base unit in the local currency).
+
+ // Add a payment to the receipt with the total amount paid, card details, etc.
+ global.apis.pos.addReceiptPayment(
+ new global.apis.pos.ReceiptPayment(
+ global.apis.i18n.currencyMinorToMajor(amount),
+ "card", // Payment type. Accepted values are card, ach, crypto, cash,
+ // check, account, and free. Other types will be displayed as-is.
+ "Demo Card\nCardholder Name, etc\nMore info for receipt" // Additional text for receipt
+ )
+ );
+
+
+ // Must return boolean false if the payment failed.
+ // Otherwise it will be assumed it succeeded.
+ // If an error is encountered, handle it and return false.
+ // It's recommended to display a short "payment failed" error
+ // message via global.apis.alert, and outputting more details
+ // via global.apis.pos.addOnscreenPaymentLog.
+
+ // If capture is false, perform an authorization but don't capture,
+ // and return a value you can use to identify the authorization later
+ // and complete it. The value will be passed back to finishPayment, below.
+ // This is used mainly for the self-serve kiosk mode, in case the label fails
+ // to be purchased/generated by the carrier.
+ },
+ cancelCheckout: function () {
+ // The user has requested the card transaction be canceled before it completes.
+ // Reset the terminal to its resting state, clear its screen, etc.
+ },
+ finishPayment: async function ({checkoutResponse}) {
+ // Finish a payment that was authorized but not captured
+ // because checkout() was called with capture = false.
+ // If payment was already captured and added
+ // to the receipt, just return true.
+ global.apis.pos.addReceiptPayment(
+ new global.apis.pos.ReceiptPayment(
+ global.apis.i18n.currencyMinorToMajor(amount),
+ "card",
+ "Demo Card\nCardholder Name, etc\nMore info for receipt"
+ )
+ );
+ },
+ updateCartDisplay: function (receipt) {
+ // Show transaction data on the card reader display.
+ // This function is called when the "cart" or total changes.
+ // `receipt` is a receipt object, see docs for details.
+ },
+ checkoutSavedMethod: async function ({customerID, paymentMethodID, amount}) {
+ // Same as checkout() except using a payment method already on file.
+ // customerID and paymentMethodID are provided by getSavedPaymentMethods below.
+
+ // Must return true upon success.
+ // If the payment is not successful, and you didn't throw an Error to show the user,
+ // then `return false` instead and it'll appear that the user's action to start the payment did nothing.
+ return true;
+ },
+ saveCardForOfflineUse: async function ({statusCallback, customerUUID, name,
+ company, street1, street2, city, state, zip, country, email, phone}) {
+ // Use the card reader to capture an in-person card and save it for offline use.
+ // Provided details are the customer's info, which might be empty strings except for the customerUUID.
+ // Saved card details must be tied to the customerUUID, as that's how saved cards are looked up.
+
+ // statusCallback(string, boolean) updates the progress message on the cashier's screen.
+ // If the boolean is true, the progress message is replaced with a confirmation message.
+ statusCallback("Saving card details...", false);
+
+ return true; // Card saved to customer
+ // If an error occurred, you can throw it and the error
+ // message will be displayed to the cashier.
+ // Alternatively, return boolean false and display the error
+ // yourself with global.apis.alert(message, title) or something.
+ },
+ cancelSaveCardForOfflineUse: function () {
+ // Cancel the process running in saveCardForOfflineUse() at the user/cashier's request.
+ },
+ getSavedPaymentMethods: async function ({customerUUID}) {
+ // Return all saved payment methods tied to the provided customer UUID.
+ return [{
+ customer: "<internal string referencing the customer>", // Passed to checkoutSavedMethod as customerID
+ customer_uuid: customerUUID,
+ id: "<card/payment method identifier>", // Passed to checkoutSavedMethod as paymentMethodID
+ type: "card", // Payment type. Accepted values are card, ach, crypto, cash, check, account, and free.
+ label: "Visa debit x1234 (exp. 12/29)", // Label for payment method
+ label_short: "Visa debit x1234" // Abbreviated label for payment method
+ }];
+ },
+ deleteSavedPaymentMethod: async function ({customerUUID, customerID, paymentMethodID}) {
+ // Delete the payment method identified by paymentMethodID
+ // and tied to the PostalPoint customerUUID and the card processor customerID.
+ // If unable to delete, throw an error and the error message
+ // will be displayed to the cashier.
+ }
+});
+Register as a cryptocurrency payment processor.
+Kind: static method of pos
| Param | +Type | +Description | +
|---|---|---|
| f | +Object |
+Payment processor functions | +
Example
+
global.apis.pos.registerCryptoProcessor({
+ name: "Demo Crypto", // Shown in PostalPoint settings menu
+ init: async function () {
+ // This is run after PostalPoint starts,
+ // and before any other crypto functions are called.
+ },
+ checkout: async function ({amount}) {
+ // Run the checkout process.
+ // amount is the amount of fiat currency to collect,
+ // in pennies (or the local equivalent).
+
+ // If an error is encountered during processing,
+ // display an error message in a dialog and return boolean false.
+ // If this function returns anything except false or undefined,
+ // and doesn't throw an error,
+ // it is assumed the payment was successful.
+
+ // Adds a line of text visible to the cashier
+ global.apis.pos.addOnscreenPaymentLog("Getting crypto payment...");
+
+ // Display a web page (i.e. with a payment QR code)
+ // to the customer on the customer-facing display.
+ global.apis.ui.setCustomerScreen("<html></html>", "html");
+ global.apis.ui.setCustomerScreen("https://postalpoint.app", "raw");
+
+ // Poll the status of the crypto transaction
+ var paymentComplete = false;
+ do {
+ await global.apis.util.delay(1000);
+ paymentComplete = true;
+ } while (paymentComplete != true);
+
+ global.apis.pos.addReceiptPayment(
+ new global.apis.pos.ReceiptPayment(
+ global.apis.i18n.currencyMinorToMajor(amount),
+ "crypto", // Payment type.
+ "Bitcoin\n0.00001234 BTC" // Additional text for receipt
+ )
+ );
+ global.apis.pos.addOnscreenPaymentLog("Payment successful!");
+ global.apis.ui.clearCustomerScreen();
+ },
+ cancelCheckout: function () {
+ // The user requested to cancel the payment.
+ // Reset things accordingly.
+ global.apis.ui.clearCustomerScreen();
+ },
+ isConfigured: function () {
+ // Is this plugin properly setup
+ // and able to process payments?
+ // If not, return false.
+ // This determines if the crypto payment method button will be shown.
+ return true;
+ }
+});
+ObjectGet the sales tax percentage to charge on a shipping service ReceiptItem.
+Kind: static method of pos
+Returns: Object - {type: "", percent: 0.15}
+type is an empty string for taxing the entire price, or "markup" for only adding tax to the markup amount.
+percent is the tax percentage. A value of 0.15 means a 15% tax.
objectPrinting to connected printers
+Kind: global namespace
+objectPromise.<Object>ObjectPrint a 300 DPI image on the shipping label printer, centered on a 4x6 inch label. Image is automatically scaled to 200 DPI if required by the printer.
+Kind: static method of print
| Param | +Type | +Description | +
|---|---|---|
| image | +ArrayBuffer | Buffer | Uint8Array | string | Jimp |
+image data, as a Jimp image object, raw PNG bytes, or a URL (http/https) string. 1200x1800 or 800x1200 images are scaled to 4x6 inches. Other image sizes are assumed to be 300 DPI and are centered on the shipping label. Image orientation is rotated to match the label orientation. | +
Promise.<Object>Get the receipt printer interface. See the ReceiptPrinter docs for available functions.
+Kind: static method of print
+
Send raw data (generated by the printer interface) to the receipt printer.
+Kind: static method of print
| Param | +Type | +Description | +
|---|---|---|
| data | +string | Uint8Array | Array.<string> | Array.<Uint8Array> |
+Data to send to printer. | +
ObjectConvert a Jimp image object to 1-bit monochrome image data before sending image data to a printer interface. Optionally scales the image to a different DPI before conversion.
+Kind: static method of print
+Returns: Object - - Example: {width: 300, height: 200, img: Uint8Array}. Pass img to drawImage on a printer interface.
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| jimpImage | +Jimp |
++ | + |
| [dpiFrom] | +number |
+300 |
+Original image DPI. | +
| [dpiTo] | +number |
+300 |
+New image DPI. | +
objectDefine custom reports for the user.
+ +Kind: static method of reports
| Param | +Type | +Description | +
|---|---|---|
| name | +string |
+Report name | +
| onload(startDate,endDate) | +function |
+Called when the report is loaded, with start and end Date objects. See example. | +
| date | +boolean |
+If the report requires a date range be selected. | +
Example
+
global.apis.reports.registerReport("sample", function (startDate, endDate) {
+
+ // Note about column datatypes:
+ // Use "string" for the datatype, except for the special cases listed here.
+ // Other datatypes may be added in the future, so use "string"
+ // unless you like unexpected behavior!
+ //
+ // datetime: Column is a UNIX timestamp (in seconds).
+ // It is displayed as a formatted date and time string.
+ // receiptid: Column is a PostalPoint receipt ID number. Displayed as a link.
+ // Clicking the ID will fetch and open the receipt in a popup.
+ // userid: Column contains an employee ID number from the PostalPoint database.
+ // It is queried in the database and replaced with the employee's name,
+ // or with an empty string if the ID lookup has no results.
+ // money: Column is a number that will be formatted as currency for display.
+ // percent: Column is a percent value (as 12.3, not .123) and will be formatted
+ // with a trailing % sign and rounded to two decimal places.
+
+ // Single-table report
+ return {
+ table: {
+ header: ["Column 1", "Column 2"],
+ datatypes: ["string", "string"],
+ rows: [
+ ["Row 1 Col 1", "Row 1 Col 2"],
+ ["Row 2 Col 1", "Row 2 Col 2"]
+ ]
+ }
+ };
+
+ // Multiple-table report
+ return {
+ multitable: true,
+ table: {
+ titles: ["Report 1 Title", "Report 2 Title"],
+ header: [["Report 1 Column 1", "Report 1 Column 2"], ["Report 2 Column 1", ...]],
+ datatypes: [["string", "string"], ["string", "string"]],
+ rows: [
+ [
+ ["Report 1 Row 1 Col 1", "Report 1 Row 1 Col 2"],
+ ["Report 1 Row 2 Col 1", "Report 1 Row 2 Col 2"]
+ ],
+ [
+ ["Report 2 Row 1 Col 1", "Report 2 Row 1 Col 2"],
+ ["Report 2 Row 2 Col 1", "Report 2 Row 2 Col 2"]
+ ]
+ ]
+ }
+ }
+}, true);
+objectPostalPoint provides a UI for user-configurable plugin settings. +See exports.config in examples/basic-demo/plugin.js for details. +Settings are typically very short strings. Do not store data in settings. +For data storage, see Storing Data. Non-string settings values are transparently converted to/from JSON objects. +Use a unique key name prefix for your plugin to prevent key name conflicts. +Reverse domain style is recommended (i.e. "com.example.pluginname.keyname").
+Kind: global namespace
+object
+*Get a setting.
+Kind: static method of settings
| Param | +Type | +Description | +
|---|---|---|
| key | +string |
+Setting key/ID | +
| defaultValue | +* |
+Value to return if setting has no stored value. | +
Set a setting.
+Kind: static method of settings
| Param | +Type | +Description | +
|---|---|---|
| key | +string |
+Setting key/ID | +
| value | +string |
+Value to set. | +
objectAdd custom carrier and rates, and adjust markup.
+Kind: global namespace
+objectObjectPromise.<Object>Promise.<number>stringstringKind: static class of shipping
+
A class representing an address.
+ +ObjectGet data for a ZIP Code.
+Kind: static method of shipping
+Returns: Object - Data about the ZIP code. See example. Fields may be empty if not available. Type may be "STANDARD", "UNIQUE", "PO BOX", or "MILITARY".
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| zipcode | +string |
++ | ZIP or postal code. | +
| country | +string |
+"US" |
+Currently only "US" and "CA" are supported. | +
Example
+
Promise.<Object>Get a parcel's packaging type from PostalPoint's internal ID for it.
+Kind: static method of shipping
+Returns: Promise.<Object> - See examples.
| Param | +Type | +
|---|---|
| id | +number |
+
Example
+
{
+ id: 100,
+ type: "Parcel",
+ img: "box.png",
+ name: "Box",
+ service: "",
+ l: -1,
+ w: -1,
+ h: -1,
+ weight: true,
+ hazmat: true,
+ source: "Customer"
+}
+{
+ id: 1,
+ type: "FlatRateEnvelope",
+ img: "pm-fres.png",
+ name: "Flat Rate Envelope",
+ service: "Priority",
+ l: -2,
+ w: -2,
+ h: -2,
+ weight: false,
+ hazmat: true,
+ usps_supplied: true,
+ envelope: true,
+ source: "USPS",
+ skus: ["PS00001000014", "PS00001000012", "PS00001000027", "PS00001000064", "PS00001001921", "PS00001035000", "PS00001036014", "PS00001128600", "https://qr.usps.com/epsspu?p=30", "https://qr.usps.com/epsspu?p=8"]
+}
+{
+ id: 201,
+ type: "UPSLetter",
+ img: "ups-env.png",
+ name: "Envelope",
+ carrier: "UPS",
+ l: -2,
+ w: -2,
+ h: -2,
+ weight: true,
+ hazmat: true,
+ source: "OtherCarrier"
+}
+Promise.<number>Calculate the retail price for a shipment rate based on the configured margin settings.
+Kind: static method of shipping
+Returns: Promise.<number> - The amount to charge the customer
| Param | +Type | +Description | +
|---|---|---|
| cost | +number |
+Cost of shipment to business | +
| retail | +number |
+Default retail price from label provider | +
| carrier | +string |
+Shipment carrier | +
| service | +string |
+Shipment service | +
| weightOz | +number |
+The weight of the shipment in ounces, or null if not available. | +
| packaging | +string |
+An empty string if not available, or "Letter", "FlatRateEnvelope", etc. | +
stringConverts the carrier ID string into a consistent and human-readable name.
+Kind: static method of shipping
| Param | +Type | +
|---|---|
| carrierId | +string |
+
stringConverts the service ID string into a consistent and human-readable name. Set the carrier ID for better results.
+Kind: static method of shipping
| Param | +Type | +Default | +
|---|---|---|
| serviceId | +string |
++ |
| carrier | +string |
+"USPS" |
+
Register the plugin as a shipping rate and label provider. See the Shipping example plugin.
+Kind: static method of shipping
| Param | +Type | +Description | +
|---|---|---|
| getRates | +function |
+A function passed a Parcel object to get rates for. Returns a Promise that resolves to an array of rate objects. | +
| purchase | +function |
+A function passed a rate ID to purchase. Returns a Promise that resolves to the label information. | +
| idPrefix | +string |
+A unique string that will be prefixing all rate IDs from this plugin. | +
Example
+
// getRates sample return value:
+[{
+ rateid: `${idPrefix}_${global.apis.util.uuid.v4()}`,
+ carrier: "CarrierID",
+ carrierName: "Carrier Name",
+ service: "CARRIER_SERVICE_ID",
+ cost_rate: 10,
+ retail_rate: 15,
+ delivery_days: 3,
+ delivery_date: null,
+ guaranteed: true,
+ serviceName: "Service Name",
+ color: "green" // Rate card color
+}]
+// purchase sample return value:
+{
+ label: labelImageToPrint,
+ labeltype: "PNG",
+ receiptItem: ReceiptItem,
+ tracking: "12345678901234567890",
+ cost: 10.0,
+ price: 15.0,
+ carrier: "Carrier Name",
+ service: "Service Name",
+ delivery_days: 3,
+ delivery_date: 1234567890, // UNIX timestamp
+ to: toAddressLines // Array of strings
+}
+Register the plugin to modify PostalPoint's shipping markup calculation during shipment rating.
+Kind: static method of shipping
+Throws:
Error Only one plugin may register with this function;
+any subsequent attempts to register will throw an Error.| Param | +Type | +Description | +
|---|---|---|
| markupFn | +function |
+A function that must return either the retail price to charge for this rate, or false to opt-out of setting this particular rate. |
+
Example
+
global.apis.shipping.registerMarkupCalculator(
+ // Parameters:
+ // cost: Cost to shipper
+ // retail: Carrier-suggested retail price
+ // suggested: PostalPoint-suggested retail (default margin calc)
+ // carrier: Shipping carrier name
+ // service: Shipping service code
+ // weightOz: The weight of the shipment in ounces, or null if not available.
+ // packaging: An empty string if not available, or "Letter", "FlatRateEnvelope", etc. See https://docs.easypost.com/docs/parcels#predefined-package
+ // parcel: The Parcel object for this shipment. May be null for some rate-only requests without a shipment, such as USPS price calculations.
+ function (cost, retail, suggested, carrier, service, weightOz, packaging, parcel) {
+ if (carrier == "USPS") {
+ if (service == "First-Class Mail") {
+ // Handle First-Class Mail differently if it's a 1oz letter (i.e. Forever stamp)
+ if (weightOz <= 1 && packaging == "Letter") {
+ return retail + 0.05;
+ } else {
+ return retail + 0.25;
+ }
+ }
+ // Handle flat rate envelopes differently
+ if (global.apis.shipping.getServiceName(service, carrier) == "Priority Mail" && packaging == "FlatRateEnvelope") {
+ return retail + 1.0;
+ }
+ return suggested + 2.0; // Charge the PostalPoint-calculated amount plus $2
+ } else {
+ return cost * 2; // Charges the customer double the shipment's cost.
+ }
+ }
+);
+Add a shipping insurance provider.
+Kind: static method of shipping
| Param | +Type | +Description | +
|---|---|---|
| id | +string | null |
+Unique ID for the provider. Will be autogenerated if null. | +
| name | +string |
+Human-readable name for the provider. Shown as the card heading on the Insurance section of the Ship screen. | +
| cardText | +string |
+Text or HTML to display on the Ship screen card for this provider. | +
| maxValue | +number |
+The largest number that will be accepted for the "Insured for" value. | +
| getQuote | +function |
+Returns the cost and retail price for insuring the parcel, or a Promise that resolves into the same. See the example for details. | +
| insure | +function |
+Insure the parcel and add the insurance details to the receipt. See example. | +
Example
+
async function getQuote(value, parcel, carrier, service) {
+ // Do math, etc
+ var cost = value / 100;
+
+ return {
+ cost: cost,
+ retail: cost * 2
+ };
+ // Or, to remove this shipping rate from the list,
+ // because the shipment/carrier/service combination
+ // is not eligible for insurance:
+ return false;
+}
+
+async function insure(value, parcel, carrier = "USPS", service = "Priority", trackingNumber = "94055...") {
+ // Purchase the insurance
+ var cost = value / 100;
+ var retailPrice = cost * 2;
+ var costPrice = cost;
+
+ var receiptitem = new global.apis.pos.ReceiptItem(`sampleinsurance_${trackingNumber}`,
+ "Sample Insurance",
+ "Insured for " + global.apis.i18n.moneyString(value),
+ retailPrice, 1, costPrice, 0
+ );
+ receiptitem.merch = true;
+ receiptitem.category = "Shipping Insurance";
+ receiptitem.barcode = trackingNumber;
+ global.apis.pos.addReceiptItem(receiptitem);
+}
+
+global.apis.shipping.registerInsuranceProvider(
+ "sampleproviderid", "Sample Insurance",
+ "Insurance coverage from Sample Insurance. $1 per $100 of value.",
+ 5000, getQuote, insure);
+objectGet and set data.
+Kind: global namespace
+object*Promise.<*>Promise*Get a value from the small data storage, using localStorage or a similar mechanism (may change in the future).
+Kind: static method of storage
| Param | +Type | +Description | +
|---|---|---|
| key | +string |
+Storage item key/ID | +
| defaultValue | +* |
+Value to return if the item key doesn't have a stored value. | +
Set a value in the small data storage, using localStorage or a similar mechanism (may change in the future).
+Kind: static method of storage
| Param | +Type | +Description | +
|---|---|---|
| key | +string |
+Storage item key/ID | +
| value | +* |
+Value to store. | +
Get a value in the large data storage. Unserialized from a JSON file on disk.
+Kind: static method of storage
| Param | +Type | +Description | +
|---|---|---|
| key | +string |
+Storage item key/ID | +
| defaultValue | +* |
+Value to return if the item key doesn't have a stored value. | +
Set a value in the large data storage. Serialized to JSON and stored on disk as a file.
+Kind: static method of storage
| Param | +Type | +Description | +
|---|---|---|
| key | +string |
+Storage item key/ID | +
| value | +* |
+Value to store. | +
Promise.<*>Get a value from the database storage. Unlike other storage types, values in the database are available on all PostalPoint installations in a single location.
+Kind: static method of storage
| Param | +Type | +Description | +
|---|---|---|
| key | +string |
+Storage item key/ID | +
| defaultValue | +* |
+Value to return if the item key doesn't have a stored value. | +
PromiseSet a value in the database storage. Non-string values are serialized to JSON. Unlike other storage types, values in the database are available on all PostalPoint installations in a single location.
+Kind: static method of storage
| Param | +Type | +Description | +
|---|---|---|
| key | +string |
+Storage item key/ID | +
| value | +* |
+Value to store. | +
objectInteract with and modify the PostalPoint user interface.
+Kind: global namespace
+objectundefinedundefinedObjectAdd a page to the Tools screen. If type is set to "function", the page argument +will be run as a function and will not be expected to return a page component. +Framework7 Page Component documentation
+Kind: static method of ui
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| page | +string | function |
++ | Page content as a Framework7 component page. If page is a string ending in .f7 it is treated as a file path and the page content will be loaded from disk. If page is any other string, it is treated as the page content. If page is a function, it will be called and must return the page content (unless type is set to "function", see examples) |
+
| title | +string |
++ | Page title. | +
| id | +string |
++ | Page ID. Make it unique, or pass an empty string to be assigned a random ID. | +
| description | +string |
++ | Description of this tool for its card on the Tools screen. | +
| cardTitle | +string |
++ | Title of the card for this page on the Tools screen. | +
| icon | +string |
++ | FontAwesome icon class, for example, "fa-solid fa-globe". FontAwesome Pro solid, regular, light, and duotone icons are available. | +
| type | +string |
+"page" |
+What kind of data is supplied by page: "page" or "function". |
+
Example
+
// Full plugin that displays an alert when the card is clicked on the Tools page
+exports.init = function () {
+ global.apis.ui.addToolsPage(
+ displayMessage,
+ "click me",
+ "clickmecard",
+ "Click here to see a message",
+ "Click This Card",
+ "fa-solid fa-arrow-pointer",
+ "function"
+ );
+}
+
+function displayMessage() {
+ global.apis.alert("Card clicked");
+}
+// Open a dynamically-generated page
+function rollDice() {
+ var randomNumber = Math.round(Math.random() * 6) + 1;
+ return `<div class="page">
+ <div class="navbar">
+ <div class="navbar-bg"></div>
+ <div class="navbar-inner">
+ <a href="#" class="link back">
+ <i class="icon icon-back"></i>
+ </a>
+ <div class="title">Random Number</div>
+ </div>
+ </div>
+ <div class="page-content">
+ <div class="block">
+ <h1>You rolled ${randomNumber}</h1>
+ </div>
+ </div>
+ </div>`;
+}
+global.apis.ui.addToolsPage(
+ rollDice,
+ "Random",
+ "randomnumbercard",
+ "Click here for a random number",
+ "Random Number",
+ "fa-regular fa-dice",
+ "page"
+ );
+// Open a page from a file.
+// See https://framework7.io/docs/router-component#single-file-component
+global.apis.ui.addToolsPage(
+ global.apis.getPluginFolder("example-plugin") + "/page.f7",
+ "Page",
+ "filepage",
+ "Open page.f7 from the plugin installation folder",
+ "Open Custom Page",
+ "fa-regular fa-file",
+ "page"
+ );
+undefinedAdd a custom tab to the PostalPoint home screen. Works almost the same as addToolsPage.
+Kind: static method of ui
| Param | +Type | +Description | +
|---|---|---|
| content | +string | function |
+Tab content. It is rendered/processed when the user navigates to the Home screen and clicks the tab; if the user navigates to a different screen and back to Home, it will be re-rendered. If content is a string ending in .f7 it is treated as a file path and the content will be loaded from disk. If content is any other string, it is treated as the content. If content is a function, it will be called and must return the content. |
+
| title | +string |
+Tab title. Keep it short; depending on screen size and tab count, you have as little as 150px of space. | +
| icon | +string |
+FontAwesome icon displayed above the tab title. | +
| id | +string |
+Tab ID. Make it unique, or pass an empty string to be assigned a random ID. If addHomeTab is called with a tab ID that is already registered, it will be overwritten. | +
Example
+
global.apis.ui.addHomeTab("<div class='block'>Hello</div>", "Hello Tab", "fa-duotone fa-hand-wave", "hellotab");
+function renderTab() {
+ return "<template><div><h1>${hellovar}</h1></div></template><script>export default (props, {$on, $update, $f7}) => {var hellovar = 'hello world'; return $render;}</script>";
+}
+global.apis.ui.addHomeTab(renderTab, "Hello Template", "fa-duotone fa-file-code", "hellotemplatetab");
+undefinedShow a notification with a loading icon.
+Kind: static method of ui
| Param | +Type | +Description | +
|---|---|---|
| title | +string |
+The message to show on the spinner. | +
| text | +string |
+Optional. Body text on the spinner. | +
| subtitle | +string |
+Optional. Sub-heading under the title. |
+
Close the notification opened by showProgressSpinner.
Kind: static method of ui
+
Open the native OS default browser to the URL given.
+Kind: static method of ui
| Param | +Type | +
|---|---|
| url | +string |
+
Open a web browser inside PostalPoint. The browser has forward/back/close buttons.
+Kind: static method of ui
| Param | +Type | +
|---|---|
| url | +string |
+
Example
+
global.apis.ui.openInternalWebBrowser("https://postalpoint.app");
+global.apis.eventbus.on("browserNavigate", function (newUrl) {
+ global.apis.alert(`New URL: ${newUrl}`, "Browser Navigated");
+ if (newUrl == "https://closeme.com") {
+ global.apis.eventbus.emit("browserCloseRequest");
+ }
+});
+Clear any custom content on the customer-facing display, defaulting back to blank/receipt/shipping rates, as applicable.
+Kind: static method of ui
+
Render content on the customer-facing display.
+Encodes content as a data URI (example: data:text/html;charset=utf-8,${content})
+and renders on the customer-facing display. If type is html, renders the string as HTML.
+If type is pdf, displays a PDF viewer. If type is raw, functions like setting an iframe's
+src to content. All other type values are rendered as text/plain.
+To display the iframe in a card centered on the screen, set displayInCard to true
+and pass the desired dimensions (w, h) of the card in px.
+If the requested size is larger than the available screen space, the card will instead
+fill the available space.
+Warning: Do not load third-party websites, this is a security risk.
+Wrap it in a
Kind: static method of ui
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| content | +string |
++ | Page content. | +
| type | +string |
+"html" |
+Format of the content. One of "html", "pdf", "raw", "body", or "text". |
+
| displayInCard | +boolean |
+false |
+Set to true to wrap the content in a card UI. | +
| cardSize | +Array.<number> |
+[300,300 |
+Size of the card UI if displayInCard == true. | +
| displayStatusBar | +boolean |
+true |
+Whether the bar on the bottom of the screen should be visible, containing the store logo and scale weight. | +
Example
+
// How content is converted by PostalPoint before display:
+if (type == "html") {
+ customerScreenContent = `data:text/html;charset=utf-8,${content}`;
+} else if (type == "pdf") {
+ customerScreenContent = `data:application/pdf,${content}`;
+} else if (type == "raw") {
+ global.customerScreenContent = `${content}`;
+} else if (type == "body") {
+ customerScreenContent = `data:text/html;charset=utf-8,<!DOCTYPE html>
+ <meta charset="utf-8">
+ <title></title>
+ <style>
+ html, body {margin: 0; padding: 0; font-family: Roboto, Ubuntu, Arial, sans-serif;}
+ h1, h2, h3 {margin: 0;}
+ </style>
+ <div id="maindiv">${content}</div>`;
+} else {
+ customerScreenContent = `data:text/plain;charset=utf-8,${content}`;
+}
+Show a signature pad on the customer-facing display. +When the customer indicates the signature is finished, +the customerSignatureCollected event is emitted with the data +{"svg": "data:image/svg+xml;base64,...", "png": "data:image/png;base64,..."}
+Kind: static method of ui
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| title | +string |
+null |
+Display a title/header on the customer screen. Currently ignored, but may be used in the future. | +
| terms | +string | boolean |
+false |
+Set to a string to display terms and conditions or other text content next to the signature pad. | +
| termstype | +string |
+"body" |
+"html", "pdf", "raw", or "body". See setCustomerScreen() | +
Example
+
global.apis.ui.collectSignatureFromCustomerScreen("", "<p>By signing, you agree to pay us lots of money</p>", "body");
+global.apis.eventbus.on("customerSignatureCollected", function (sigdata) {
+ const pngDataURL = sigdata.png;
+ const svgDataURL = sigdata.svg;
+});
+Cancels customer signature collection and returns the customer-facing display to normal operation.
+Kind: static method of ui
+Example
+
Erase the signature drawn on the customer-facing display. +Note that the customer is also provided a button to do this.
+Kind: static method of ui
+Example
+
ObjectDescribes if the customer-facing display is currently enabled, +and if it supports customer touch interaction.
+Kind: static method of ui
+Returns: Object - {"enabled": true, "touch": true}
+Example
+
objectAccess data about employees.
+Kind: global namespace
+objectUsernumberPromise.<User>Promise.<Array.<User>>Kind: static class of user
+Properties
| Name | +Type | +Description | +
|---|---|---|
| id | +number |
++ |
| name | +string |
++ |
| pass | +string |
++ |
| barcode | +string |
++ |
| enabled | +boolean |
++ |
| hasPassword() | +function |
+Returns true if the user has a password set, else false. | +
| checkPassword(string) | +function |
+Returns true if the provided password matches the user's password, or if there is no password set. | +
| icon(number) | +function |
+Returns a SVG data URI with a procedurally-generated icon for the user. Size defaults to 50px if not specified. | +
A User object.
+| Param | +Type | +
|---|---|
| id | +number |
+
| name | +string |
+
| password | +string |
+
| barcode | +string |
+
| enabled | +boolean |
+
UserGet the user currently logged in.
+Kind: static method of user
+
numberGet the current user's ID number.
+Kind: static method of user
+
Promise.<User>Look up the User for an ID number.
+Kind: static method of user
+
Promise.<Array.<User>>Get a list of all users in the system.
+Kind: static method of user
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| [managerMode] | +boolean |
+false |
+If false, list only active/enabled users, and if no users, return a default user account (user ID -1). If true, return all users in the database, and don't return a default account if the list is empty (return an empty list instead). | +
objectVarious utility functions: HTTP, time/date, barcode creation, clipboard, etc.
+Kind: global namespace
+objectobjectstringstringobjectobjectPromise.<string>Promise.<Array.<Object>>Promise.<(string|Blob|ArrayBuffer|Object)>Promise.<(string|Blob|ArrayBuffer|Object)>objectArray.<string>Array.<string>objectnumbernumbernumberstringstringstringobjectPromise.<boolean>objectPromise.<Buffer>Promise.<string>objectstringbooleanPromiseobjectUnique ID generators.
+Kind: static namespace of util
objectstringstringstringGenerate a UUID string
+Kind: static method of uuid
+Returns: string - UUID v4 with dashes: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
+
stringGenerate a short random alphanumeric string.
+Kind: static method of uuid
+Returns: string - A string of length length, from the character set "acdefhjkmnpqrtuvwxy0123456789".
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| [length] | +number |
+16 |
+String character count. | +
objectHTTP requests and webhooks.
+Kind: static namespace of util
objectobjectPromise.<string>Promise.<Array.<Object>>Promise.<(string|Blob|ArrayBuffer|Object)>Promise.<(string|Blob|ArrayBuffer|Object)>objectUse webhooks via a PostalPoint cloud relay service.
+Kind: static namespace of http
objectPromise.<string>Promise.<Array.<Object>>Promise.<string>geturl - Returns a public URL that can be used as a webhook target/endpoint for third-party integrations.
+Kind: static method of webhook
+Returns: Promise.<string> - A URL for the webhook.
| Param | +Type | +Description | +
|---|---|---|
| sourcename | +string |
+Unique identifier for the webhook | +
Promise.<Array.<Object>>poll - Returns an array of webhook payloads received by the webhook identified by sourcename.
Kind: static method of webhook
+Returns: Promise.<Array.<Object>> - Payloads as received by the webhook relay service.
| Param | +Type | +Description | +
|---|---|---|
| sourcename | +string |
+Unique identifier for the webhook | +
Example
+
[
+ {
+ // Unique ID. Used for ack(webhookid).
+ id: 123,
+
+ // UNIX timestamp (in seconds) of when the data was received by the webhook URL.
+ timestamp: 1234567890,
+
+ // Source name set in geturl()
+ source: "sourcename",
+
+ // JSON string of all the HTTP headers sent to the webhook URL.
+ headers: "{'Content-Type': 'application/json'}",
+
+ // Entire HTTP request body sent to the webhook URL.
+ body: ""
+ }
+]
+Acknowledge receipt of a webhook payload, deleting it from the relay server. +Webhook payload is only queued for deletion, so polling may still return it for a short time.
+Kind: static method of webhook
| Param | +Type | +Description | +
|---|---|---|
| webhookid | +number |
+Numeric unique ID received with the payload. See poll. |
+
Promise.<(string|Blob|ArrayBuffer|Object)>post - Fetch a HTTP POST request.
+Kind: static method of http
+Returns: Promise.<(string|Blob|ArrayBuffer|Object)> - The server response body. See responseType parameter.
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| url | +string |
++ | + |
| data | +Object.<string, string> |
++ | POST data key/value list | +
| [responseType] | +string |
+"text" |
+"text", "blob", "buffer", or "json" | +
| [headers] | +Object.<string, string> |
++ | HTTP headers to send. Defaults to {"Content-Type": "application/json"}. |
+
| [method] | +string |
+"POST" |
++ |
| [continueOnBadStatusCode] | +boolean |
+false |
+If false, throws an Error when the HTTP response code is not 2XX. If true, ignores the response code and proceeds as normal. | +
| [timeoutSeconds] | +number |
+15 |
+Aborts the request (timeout) after this many seconds. | +
Promise.<(string|Blob|ArrayBuffer|Object)>fetch - Fetch a HTTP GET request.
+Kind: static method of http
+Returns: Promise.<(string|Blob|ArrayBuffer|Object)> - The server response body. See responseType parameter.
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| url | +string |
++ | + |
| [responseType] | +string |
+"text" |
+"text", "blob", "buffer", or "json" | +
| [timeoutSeconds] | +number |
+15 |
+Aborts the request (timeout) after this many seconds. | +
objectString manipulation functions.
+Kind: static namespace of util
objectArray.<string>Array.<string>Array.<string>Split a string with a separator regex.
+Kind: static method of string
| Param | +Type | +Description | +
|---|---|---|
| input | +string |
+Input string | +
| separator | +string |
+Passed to new RegExp(separator, 'g') |
+
| [limit] | +number |
+Maximum number of splits to perform | +
Array.<string>Split a string into chunks of length chunksize.
Kind: static method of string
| Param | +Type | +Description | +
|---|---|---|
| input | +string |
+Input string | +
| chunksize | +string |
+Number of characters per chunk | +
objectDate and time functions
+Kind: static namespace of util
objectnumbernumbernumberstringstringstringnumberGet the current UNIX timestamp in seconds.
+Kind: static method of time
+
numberGet the number of seconds between now and the given Date or UNIX timestamp in seconds.
+Kind: static method of time
| Param | +Type | +
|---|---|
| compareto | +number | Date |
+
numberParse a string date and return UNIX timestamp (in seconds).
+Kind: static method of time
| Param | +Type | +
|---|---|
| str | +string |
+
stringTake a Date or UNIX timestamp in seconds and format it to a string. +Mostly compatible with the PHP date format codes.
+Kind: static method of time
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| format | +string |
++ | "Y-m-d H:i:s", etc | +
| [timestamp] | +number | Date |
+now() |
++ |
stringFormat a UNIX timestamp (in seconds) as a localized date string.
+Kind: static method of time
| Param | +Type | +
|---|---|
| timestamp | +number |
+
stringFormat a UNIX timestamp (in seconds) as a localized time string.
+Kind: static method of time
| Param | +Type | +
|---|---|
| timestamp | +number |
+
objectOS clipboard
+Kind: static namespace of util
+
Promise.<boolean>Copy a string to the system clipboard.
+Kind: static method of clipboard
+Returns: Promise.<boolean> - True if the copy succeeded, else false.
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| text | +string |
++ | + |
| [showNotification] | +boolean |
+false |
+If true, a "Copied" notification will appear onscreen briefly. | +
objectBarcode image generation functions.
+Kind: static namespace of util
objectPromise.<Buffer>Promise.<string>Promise.<Buffer>Get a PNG image buffer of a barcode. Uses library "bwip-js".
+Kind: static method of barcode
+Returns: Promise.<Buffer> - PNG data for the barcode.
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| data | +string |
++ | + |
| [type] | +string |
+"\"code128\"" |
++ |
| [height] | +number |
+10 |
++ |
| [scale] | +number |
+2 |
++ |
| [includetext] | +boolean |
+false |
+Set true to render the barcode's content as text below the code. | +
Promise.<string>Get a PNG image of a barcode as a base64 data URI. Uses library "bwip-js".
+Kind: static method of barcode
+Returns: Promise.<string> - "data:image/png;base64,..."
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| data | +string |
++ | + |
| [type] | +string |
+"\"code128\"" |
++ |
| [height] | +number |
+10 |
++ |
| [scale] | +number |
+2 |
++ |
| [includetext] | +boolean |
+false |
+Set true to render the barcode's content as text below the code. | +
objectKind: static namespace of util
+
stringGet a human-readable country name from an ISO country code.
+Kind: static method of geography
| Param | +Type | +Description | +
|---|---|---|
| iso | +string | number |
+2 or 3 letter country code, or numeric country code. | +
booleanCompare two objects for equality. See https://stackoverflow.com/a/16788517
+Kind: static method of util
+Returns: boolean - True if equal, else false.
| Param | +Type | +
|---|---|
| a | +* |
+
| b | +* |
+
PromisePause execution for some amount of time in an async function, i.e., returns a Promise that resolves in some number of milliseconds.
+Kind: static method of util
| Param | +Type | +Default | +Description | +
|---|---|---|---|
| [ms] | +number |
+1000 |
+Number of milliseconds to pause. | +
b&&(b=h),k=v*v*w,T=Math.max(b/k,k/x),T>S){v-=h;break}S=T}s.push(u={value:v,dice:m Xi))l.moveTo(0,0);else if(v>K0-Xi)l.moveTo(m*Ph(g),m*El(g)),l.arc(0,0,m,g,y,!x),p>Xi&&(l.moveTo(p*Ph(y),p*El(y)),l.arc(0,0,p,y,g,x));else{var b=g,T=y,S=g,w=y,k=v,C=v,A=s.apply(this,arguments)/2,L=A>Xi&&(n?+n.apply(this,arguments):Bd(p*p+m*m)),I=q5(XD(m-p)/2,+r.apply(this,arguments)),R=I,E=I,_,D;if(L>Xi){var O=jD(L/p*El(A)),N=jD(L/m*El(A));(k-=O*2)>Xi?(O*=x?1:-1,S+=O,w-=O):(k=0,S=w=(g+y)/2),(C-=N*2)>Xi?(N*=x?1:-1,b+=N,T-=N):(C=0,b=T=(g+y)/2)}var P=m*Ph(b),B=m*El(b),F=p*Ph(w),V=p*El(w);if(I>Xi){var $=m*Ph(T),U=m*El(T),j=p*Ph(S),ee=p*El(S),q;if(v "),t.result!==null&&g.kind!==t.kind&&Zt(t,"unacceptable node kind for !<"+t.tag+'> tag; it should be "'+g.kind+'", not "'+t.kind+'"'),g.resolve(t.result,t.tag)?(t.result=g.construct(t.result,t.tag),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):Zt(t,"cannot resolve a node with !<"+t.tag+"> explicit tag")}return t.listener!==null&&t.listener("close",t),t.tag!==null||t.anchor!==null||f}function kLe(t){var e=t.position,r,n,i,a=!1,s;for(t.version=null,t.checkLineBreaks=t.legacy,t.tagMap=Object.create(null),t.anchorMap=Object.create(null);(s=t.input.charCodeAt(t.position))!==0&&(Ci(t,!0,-1),s=t.input.charCodeAt(t.position),!(t.lineIndent>0||s!==37));){for(a=!0,s=t.input.charCodeAt(++t.position),r=t.position;s!==0&&!Os(s);)s=t.input.charCodeAt(++t.position);for(n=t.input.slice(r,t.position),i=[],n.length<1&&Zt(t,"directive name must not be less than one character in length");s!==0;){for(;Yd(s);)s=t.input.charCodeAt(++t.position);if(s===35){do s=t.input.charCodeAt(++t.position);while(s!==0&&!bc(s));break}if(bc(s))break;for(r=t.position;s!==0&&!Os(s);)s=t.input.charCodeAt(++t.position);i.push(t.input.slice(r,t.position))}s!==0&&i9(t),Xh.call(GQ,n)?GQ[n](t,n,i):BT(t,'unknown document directive "'+n+'"')}if(Ci(t,!0,-1),t.lineIndent===0&&t.input.charCodeAt(t.position)===45&&t.input.charCodeAt(t.position+1)===45&&t.input.charCodeAt(t.position+2)===45?(t.position+=3,Ci(t,!0,-1)):a&&Zt(t,"directives end mark is expected"),wm(t,t.lineIndent-1,PT,!1,!0),Ci(t,!0,-1),t.checkLineBreaks&&oLe.test(t.input.slice(e,t.position))&&BT(t,"non-ASCII line breaks are interpreted as content"),t.documents.push(t.result),t.position===t.lineStart&&zT(t)){t.input.charCodeAt(t.position)===46&&(t.position+=3,Ci(t,!0,-1));return}if(t.position ${this.parser.parseInline(t)} An error occurred: ${i.tokens?.map(n).join("")}0;){if(h=cv(s,l,r),h===u)return n[i]=s,n[a]=l,e(n);if(h>0)s=Math.floor(s/h)*h,l=Math.ceil(l/h)*h;else if(h<0)s=Math.ceil(s*h)/h,l=Math.floor(l*h)/h;else break;u=h}return t},t}function Tl(){var t=Ov();return t.copy=function(){return M5(t,Tl())},Mh.apply(t,arguments),d6e(t)}var jY=M(()=>{"use strict";Ch();CD();Iv();XY();o(d6e,"linearish");o(Tl,"linear")});function _D(t,e){t=t.slice();var r=0,n=t.length-1,i=t[r],a=t[n],s;return a{"use strict";o(_D,"nice")});function En(t,e,r,n){function i(a){return t(a=arguments.length===0?new Date:new Date(+a)),a}return o(i,"interval"),i.floor=a=>(t(a=new Date(+a)),a),i.ceil=a=>(t(a=new Date(a-1)),e(a,1),t(a),a),i.round=a=>{let s=i(a),l=i.ceil(a);return a-s0))return u;let h;do u.push(h=new Date(+a)),e(a,l),t(a);while(hEn(s=>{if(s>=s)for(;t(s),!a(s);)s.setTime(s-1)},(s,l)=>{if(s>=s)if(l<0)for(;++l<=0;)for(;e(s,-1),!a(s););else for(;--l>=0;)for(;e(s,1),!a(s););}),r&&(i.count=(a,s)=>(DD.setTime(+a),LD.setTime(+s),t(DD),t(LD),Math.floor(r(DD,LD))),i.every=a=>(a=Math.floor(a),!isFinite(a)||!(a>0)?null:a>1?i.filter(n?s=>n(s)%a===0:s=>i.count(0,s)%a===0):i)),i}var DD,LD,wu=M(()=>{"use strict";DD=new Date,LD=new Date;o(En,"timeInterval")});var uc,QY,RD=M(()=>{"use strict";wu();uc=En(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);uc.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?En(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):uc);QY=uc.range});var io,ZY,ND=M(()=>{"use strict";wu();io=En(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*1e3)},(t,e)=>(e-t)/1e3,t=>t.getUTCSeconds()),ZY=io.range});var ku,p6e,I5,m6e,MD=M(()=>{"use strict";wu();ku=En(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getMinutes()),p6e=ku.range,I5=En(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getUTCMinutes()),m6e=I5.range});var Eu,g6e,O5,y6e,ID=M(()=>{"use strict";wu();Eu=En(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3-t.getMinutes()*6e4)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getHours()),g6e=Eu.range,O5=En(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getUTCHours()),y6e=O5.range});var Ro,v6e,Bv,x6e,P5,b6e,OD=M(()=>{"use strict";wu();Ro=En(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/864e5,t=>t.getDate()-1),v6e=Ro.range,Bv=En(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>t.getUTCDate()-1),x6e=Bv.range,P5=En(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>Math.floor(t/864e5)),b6e=P5.range});function Md(t){return En(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,r)=>{e.setDate(e.getDate()+r*7)},(e,r)=>(r-e-(r.getTimezoneOffset()-e.getTimezoneOffset())*6e4)/6048e5)}function Id(t){return En(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCDate(e.getUTCDate()+r*7)},(e,r)=>(r-e)/6048e5)}var wl,Ih,B5,F5,fc,$5,z5,eX,T6e,w6e,k6e,E6e,S6e,C6e,Od,Y0,tX,rX,Oh,nX,iX,aX,A6e,_6e,D6e,L6e,R6e,N6e,PD=M(()=>{"use strict";wu();o(Md,"timeWeekday");wl=Md(0),Ih=Md(1),B5=Md(2),F5=Md(3),fc=Md(4),$5=Md(5),z5=Md(6),eX=wl.range,T6e=Ih.range,w6e=B5.range,k6e=F5.range,E6e=fc.range,S6e=$5.range,C6e=z5.range;o(Id,"utcWeekday");Od=Id(0),Y0=Id(1),tX=Id(2),rX=Id(3),Oh=Id(4),nX=Id(5),iX=Id(6),aX=Od.range,A6e=Y0.range,_6e=tX.range,D6e=rX.range,L6e=Oh.range,R6e=nX.range,N6e=iX.range});var Su,M6e,G5,I6e,BD=M(()=>{"use strict";wu();Su=En(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth()),M6e=Su.range,G5=En(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth()),I6e=G5.range});var ao,O6e,kl,P6e,FD=M(()=>{"use strict";wu();ao=En(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());ao.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:En(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)});O6e=ao.range,kl=En(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());kl.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:En(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)});P6e=kl.range});function oX(t,e,r,n,i,a){let s=[[io,1,1e3],[io,5,5*1e3],[io,15,15*1e3],[io,30,30*1e3],[a,1,6e4],[a,5,5*6e4],[a,15,15*6e4],[a,30,30*6e4],[i,1,36e5],[i,3,3*36e5],[i,6,6*36e5],[i,12,12*36e5],[n,1,864e5],[n,2,2*864e5],[r,1,6048e5],[e,1,2592e6],[e,3,3*2592e6],[t,1,31536e6]];function l(h,f,d){let p=f{"use strict";Ch();RD();ND();MD();ID();OD();PD();BD();FD();o(oX,"ticker");[F6e,$6e]=oX(kl,G5,Od,P5,O5,I5),[$D,zD]=oX(ao,Su,wl,Ro,Eu,ku)});var V5=M(()=>{"use strict";RD();ND();MD();ID();OD();PD();BD();FD();lX()});function GD(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function VD(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function Fv(t,e,r){return{y:t,m:e,d:r,H:0,M:0,S:0,L:0}}function UD(t){var e=t.dateTime,r=t.date,n=t.time,i=t.periods,a=t.days,s=t.shortDays,l=t.months,u=t.shortMonths,h=$v(i),f=zv(i),d=$v(a),p=zv(a),m=$v(s),g=zv(s),y=$v(l),v=zv(l),x=$v(u),b=zv(u),T={a:P,A:B,b:F,B:V,c:null,d:pX,e:pX,f:lCe,g:vCe,G:bCe,H:aCe,I:sCe,j:oCe,L:xX,m:cCe,M:uCe,p:$,q:U,Q:yX,s:vX,S:hCe,u:fCe,U:dCe,V:pCe,w:mCe,W:gCe,x:null,X:null,y:yCe,Y:xCe,Z:TCe,"%":gX},S={a:j,A:ee,b:q,B:oe,c:null,d:mX,e:mX,f:SCe,g:OCe,G:BCe,H:wCe,I:kCe,j:ECe,L:TX,m:CCe,M:ACe,p:Q,q:ue,Q:yX,s:vX,S:_Ce,u:DCe,U:LCe,V:RCe,w:NCe,W:MCe,x:null,X:null,y:ICe,Y:PCe,Z:FCe,"%":gX},w={a:I,A:R,b:E,B:_,c:D,d:fX,e:fX,f:tCe,g:hX,G:uX,H:dX,I:dX,j:Q6e,L:eCe,m:K6e,M:Z6e,p:L,q:j6e,Q:nCe,s:iCe,S:J6e,u:H6e,U:q6e,V:W6e,w:U6e,W:Y6e,x:O,X:N,y:hX,Y:uX,Z:X6e,"%":rCe};T.x=k(r,T),T.X=k(n,T),T.c=k(e,T),S.x=k(r,S),S.X=k(n,S),S.c=k(e,S);function k(te,re){return function(J){var K=[],ae=-1,Z=0,de=te.length,ne,Te,W;for(J instanceof Date||(J=new Date(+J));++ae{"use strict";ym();lm();o(V8e,"copyObject");$o=V8e});function U8e(t,e){for(var r=-1,n=Array(t);++r
"},r),tt.lineBreakRegex.test(t)))return t;let n=t.split(" ").filter(Boolean),i=[],a="";return n.forEach((s,l)=>{let u=Zi(`${s} `,r),h=Zi(a,r);if(u>e){let{hyphenatedStrings:p,remainingWord:m}=L_e(s,e,"-",r);i.push(a,...p),a=m}else h+u>=e?(i.push(a),a=s):a=[a,s].filter(Boolean).join(" ");l+1===n.length&&i.push(a)}),i.filter(s=>s!=="").join(r.joinWith)},(t,e,r)=>`${t}${e}${r.fontSize}${r.fontWeight}${r.fontFamily}${r.joinWith}`),L_e=am((t,e,r="-",n)=>{n=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial",margin:0},n);let i=[...t],a=[],s="";return i.forEach((l,u)=>{let h=`${s}${l}`;if(Zi(h,n)>=e){let d=u+1,p=i.length===d,m=`${h}${r}`;a.push(p?h:m),s=""}else s=h}),{hyphenatedStrings:a,remainingWord:s}},(t,e,r="-",n)=>`${t}${e}${r}${n.fontSize}${n.fontWeight}${n.fontFamily}`);o(LT,"calculateTextHeight");o(Zi,"calculateTextWidth");HL=am((t,e)=>{let{fontSize:r=12,fontFamily:n="Arial",fontWeight:i=400}=e;if(!t)return{width:0,height:0};let[,a]=vc(r),s=["sans-serif",n],l=t.split(tt.lineBreakRegex),u=[],h=qe("body");if(!h.remove)return{width:0,height:0,lineHeight:0};let f=h.append("svg");for(let p of s){let m=0,g={width:0,height:0,lineHeight:0};for(let y of l){let v=__e();v.text=y||BL;let x=D_e(f,v).style("font-size",a).style("font-weight",i).style("font-family",p),b=(x._groups||x)[0][0].getBBox();if(b.width===0&&b.height===0)throw new Error("svg element not in render tree");g.width=Math.round(Math.max(g.width,b.width)),m=Math.round(b.height),g.height+=m,g.lineHeight=Math.round(Math.max(g.lineHeight,m))}u.push(g)}f.remove();let d=isNaN(u[1].height)||isNaN(u[1].width)||isNaN(u[1].lineHeight)||u[0].height>u[1].height&&u[0].width>u[1].width&&u[0].lineHeight>u[1].lineHeight?0:1;return u[d]},(t,e)=>`${t}${e.fontSize}${e.fontWeight}${e.fontFamily}`),PL=class{constructor(e=!1,r){this.count=0;this.count=r?r.length:0,this.next=e?()=>this.count++:()=>Date.now()}static{o(this,"InitIDGenerator")}},R_e=o(function(t){return DT=DT||document.createElement("div"),t=escape(t).replace(/%26/g,"&").replace(/%23/g,"#").replace(/%3B/g,";"),DT.innerHTML=t,unescape(DT.textContent)},"entityDecode");o(qL,"isDetailedError");N_e=o((t,e,r,n)=>{if(!n)return;let i=t.node()?.getBBox();i&&t.append("text").text(n).attr("text-anchor","middle").attr("x",i.x+i.width/2).attr("y",-r).attr("class",e)},"insertTitle"),vc=o(t=>{if(typeof t=="number")return[t,t+"px"];let e=parseInt(t??"",10);return Number.isNaN(e)?[void 0,void 0]:t===String(e)?[e,t+"px"]:[e,t]},"parseFontSize");o(Vn,"cleanAndMerge");qt={assignWithDepth:Rn,wrapLabel:UL,calculateTextHeight:LT,calculateTextWidth:Zi,calculateTextDimensions:HL,cleanAndMerge:Vn,detectInit:x_e,detectDirective:wQ,isSubstringInArray:b_e,interpolateToCurve:FL,calcLabelPosition:E_e,calcCardinalityPosition:S_e,calcTerminalLabelPosition:C_e,formatUrl:T_e,getStylesFromArray:zL,generateId:GL,random:VL,runFunc:w_e,entityDecode:R_e,insertTitle:N_e,isLabelCoordinateInPath:M_e,parseFontSize:vc,InitIDGenerator:PL},SQ=o(function(t){let e=t;return e=e.replace(/style.*:\S*#.*;/g,function(r){return r.substring(0,r.length-1)}),e=e.replace(/classDef.*:\S*#.*;/g,function(r){return r.substring(0,r.length-1)}),e=e.replace(/#\w+;/g,function(r){let n=r.substring(1,r.length-1);return/^\+?\d+$/.test(n)?"\uFB02\xB0\xB0"+n+"\xB6\xDF":"\uFB02\xB0"+n+"\xB6\xDF"}),e},"encodeEntities"),Ji=o(function(t){return t.replace(/fl°°/g,"").replace(/fl°/g,"&").replace(/¶ß/g,";")},"decodeEntities"),xc=o((t,e,{counter:r=0,prefix:n,suffix:i},a)=>a||`${n?`${n}_`:""}${t}_${e}_${r}${i?`_${i}`:""}`,"getEdgeId");o(Cn,"handleUndefinedAttr");o(M_e,"isLabelCoordinateInPath")});function Ll(t,e,r,n,i){if(!e[t].width)if(r)e[t].text=UL(e[t].text,i,n),e[t].textLines=e[t].text.split(tt.lineBreakRegex).length,e[t].width=i,e[t].height=LT(e[t].text,n);else{let a=e[t].text.split(tt.lineBreakRegex);e[t].textLines=a.length;let s=0;e[t].height=0,e[t].width=0;for(let l of a)e[t].width=Math.max(Zi(l,n),e[t].width),s=LT(l,n),e[t].height=e[t].height+s}}function LQ(t,e,r,n,i){let a=new IT(i);a.data.widthLimit=r.data.widthLimit/Math.min(WL,n.length);for(let[s,l]of n.entries()){let u=0;l.image={width:0,height:0,Y:0},l.sprite&&(l.image.width=48,l.image.height=48,l.image.Y=u,u=l.image.Y+l.image.height);let h=l.wrap&&Wt.wrap,f=RT(Wt);if(f.fontSize=f.fontSize+2,f.fontWeight="bold",Ll("label",l,h,f,a.data.widthLimit),l.label.Y=u+8,u=l.label.Y+l.label.height,l.type&&l.type.text!==""){l.type.text="["+l.type.text+"]";let g=RT(Wt);Ll("type",l,h,g,a.data.widthLimit),l.type.Y=u+5,u=l.type.Y+l.type.height}if(l.descr&&l.descr.text!==""){let g=RT(Wt);g.fontSize=g.fontSize-2,Ll("descr",l,h,g,a.data.widthLimit),l.descr.Y=u+20,u=l.descr.Y+l.descr.height}if(s==0||s%WL===0){let g=r.data.startx+Wt.diagramMarginX,y=r.data.stopy+Wt.diagramMarginY+u;a.setData(g,g,y,y)}else{let g=a.data.stopx!==a.data.startx?a.data.stopx+Wt.diagramMarginX:a.data.startx,y=a.data.starty;a.setData(g,g,y,y)}a.name=l.alias;let d=i.db.getC4ShapeArray(l.alias),p=i.db.getC4ShapeKeys(l.alias);p.length>0&&DQ(a,t,d,p),e=l.alias;let m=i.db.getBoundaries(e);m.length>0&&LQ(t,e,a,m,i),l.alias!=="global"&&_Q(t,l,a),r.data.stopy=Math.max(a.data.stopy+Wt.c4ShapeMargin,r.data.stopy),r.data.stopx=Math.max(a.data.stopx+Wt.c4ShapeMargin,r.data.stopx),NT=Math.max(NT,r.data.stopx),MT=Math.max(MT,r.data.stopy)}}var NT,MT,AQ,WL,Wt,IT,YL,y2,RT,I_e,_Q,DQ,Ms,CQ,O_e,P_e,B_e,XL,RQ=M(()=>{"use strict";yr();Cj();pt();RA();gr();GA();Xt();v0();tr();Ei();NT=0,MT=0,AQ=4,WL=2;rv.yy=lv;Wt={},IT=class{static{o(this,"Bounds")}constructor(e){this.name="",this.data={},this.data.startx=void 0,this.data.stopx=void 0,this.data.starty=void 0,this.data.stopy=void 0,this.data.widthLimit=void 0,this.nextData={},this.nextData.startx=void 0,this.nextData.stopx=void 0,this.nextData.starty=void 0,this.nextData.stopy=void 0,this.nextData.cnt=0,YL(e.db.getConfig())}setData(e,r,n,i){this.nextData.startx=this.data.startx=e,this.nextData.stopx=this.data.stopx=r,this.nextData.starty=this.data.starty=n,this.nextData.stopy=this.data.stopy=i}updateVal(e,r,n,i){e[r]===void 0?e[r]=n:e[r]=i(n,e[r])}insert(e){this.nextData.cnt=this.nextData.cnt+1;let r=this.nextData.startx===this.nextData.stopx?this.nextData.stopx+e.margin:this.nextData.stopx+e.margin*2,n=r+e.width,i=this.nextData.starty+e.margin*2,a=i+e.height;(r>=this.data.widthLimit||n>=this.data.widthLimit||this.nextData.cnt>AQ)&&(r=this.nextData.startx+e.margin+Wt.nextLinePaddingX,i=this.nextData.stopy+e.margin*2,this.nextData.stopx=n=r+e.width,this.nextData.starty=this.nextData.stopy,this.nextData.stopy=a=i+e.height,this.nextData.cnt=1),e.x=r,e.y=i,this.updateVal(this.data,"startx",r,Math.min),this.updateVal(this.data,"starty",i,Math.min),this.updateVal(this.data,"stopx",n,Math.max),this.updateVal(this.data,"stopy",a,Math.max),this.updateVal(this.nextData,"startx",r,Math.min),this.updateVal(this.nextData,"starty",i,Math.min),this.updateVal(this.nextData,"stopx",n,Math.max),this.updateVal(this.nextData,"stopy",a,Math.max)}init(e){this.name="",this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,widthLimit:void 0},this.nextData={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,cnt:0},YL(e.db.getConfig())}bumpLastMargin(e){this.data.stopx+=e,this.data.stopy+=e}},YL=o(function(t){Rn(Wt,t),t.fontFamily&&(Wt.personFontFamily=Wt.systemFontFamily=Wt.messageFontFamily=t.fontFamily),t.fontSize&&(Wt.personFontSize=Wt.systemFontSize=Wt.messageFontSize=t.fontSize),t.fontWeight&&(Wt.personFontWeight=Wt.systemFontWeight=Wt.messageFontWeight=t.fontWeight)},"setConf"),y2=o((t,e)=>({fontFamily:t[e+"FontFamily"],fontSize:t[e+"FontSize"],fontWeight:t[e+"FontWeight"]}),"c4ShapeFont"),RT=o(t=>({fontFamily:t.boundaryFontFamily,fontSize:t.boundaryFontSize,fontWeight:t.boundaryFontWeight}),"boundaryFont"),I_e=o(t=>({fontFamily:t.messageFontFamily,fontSize:t.messageFontSize,fontWeight:t.messageFontWeight}),"messageFont");o(Ll,"calcC4ShapeTextWH");_Q=o(function(t,e,r){e.x=r.data.startx,e.y=r.data.starty,e.width=r.data.stopx-r.data.startx,e.height=r.data.stopy-r.data.starty,e.label.y=Wt.c4ShapeMargin-35;let n=e.wrap&&Wt.wrap,i=RT(Wt);i.fontSize=i.fontSize+2,i.fontWeight="bold";let a=Zi(e.label.text,i);Ll("label",e,n,i,a),Al.drawBoundary(t,e,Wt)},"drawBoundary"),DQ=o(function(t,e,r,n){let i=0;for(let a of n){i=0;let s=r[a],l=y2(Wt,s.typeC4Shape.text);switch(l.fontSize=l.fontSize-2,s.typeC4Shape.width=Zi("\xAB"+s.typeC4Shape.text+"\xBB",l),s.typeC4Shape.height=l.fontSize+2,s.typeC4Shape.Y=Wt.c4ShapePadding,i=s.typeC4Shape.Y+s.typeC4Shape.height-4,s.image={width:0,height:0,Y:0},s.typeC4Shape.text){case"person":case"external_person":s.image.width=48,s.image.height=48,s.image.Y=i,i=s.image.Y+s.image.height;break}s.sprite&&(s.image.width=48,s.image.height=48,s.image.Y=i,i=s.image.Y+s.image.height);let u=s.wrap&&Wt.wrap,h=Wt.width-Wt.c4ShapePadding*2,f=y2(Wt,s.typeC4Shape.text);if(f.fontSize=f.fontSize+2,f.fontWeight="bold",Ll("label",s,u,f,h),s.label.Y=i+8,i=s.label.Y+s.label.height,s.type&&s.type.text!==""){s.type.text="["+s.type.text+"]";let m=y2(Wt,s.typeC4Shape.text);Ll("type",s,u,m,h),s.type.Y=i+5,i=s.type.Y+s.type.height}else if(s.techn&&s.techn.text!==""){s.techn.text="["+s.techn.text+"]";let m=y2(Wt,s.techn.text);Ll("techn",s,u,m,h),s.techn.Y=i+5,i=s.techn.Y+s.techn.height}let d=i,p=s.label.width;if(s.descr&&s.descr.text!==""){let m=y2(Wt,s.typeC4Shape.text);Ll("descr",s,u,m,h),s.descr.Y=i+20,i=s.descr.Y+s.descr.height,p=Math.max(s.label.width,s.descr.width),d=i-s.descr.textLines*5}p=p+Wt.c4ShapePadding,s.width=Math.max(s.width||Wt.width,p,Wt.width),s.height=Math.max(s.height||Wt.height,d,Wt.height),s.margin=s.margin||Wt.c4ShapeMargin,t.insert(s),Al.drawC4Shape(e,s,Wt)}t.bumpLastMargin(Wt.c4ShapeMargin)},"drawC4ShapeArray"),Ms=class{static{o(this,"Point")}constructor(e,r){this.x=e,this.y=r}},CQ=o(function(t,e){let r=t.x,n=t.y,i=e.x,a=e.y,s=r+t.width/2,l=n+t.height/2,u=Math.abs(r-i),h=Math.abs(n-a),f=h/u,d=t.height/t.width,p=null;return n==a&&ri?p=new Ms(r,l):r==i&&na&&(p=new Ms(s,n)),r>i&&n=f?p=new Ms(r,l+f*t.width/2):p=new Ms(s-u/h*t.height/2,n+t.height):r=f?p=new Ms(r+t.width,l+f*t.width/2):p=new Ms(s+u/h*t.height/2,n+t.height):ra?d>=f?p=new Ms(r+t.width,l-f*t.width/2):p=new Ms(s+t.height/2*u/h,n):r>i&&n>a&&(d>=f?p=new Ms(r,l-t.width/2*f):p=new Ms(s-t.height/2*u/h,n)),p},"getIntersectPoint"),O_e=o(function(t,e){let r={x:0,y:0};r.x=e.x+e.width/2,r.y=e.y+e.height/2;let n=CQ(t,r);r.x=t.x+t.width/2,r.y=t.y+t.height/2;let i=CQ(e,r);return{startPoint:n,endPoint:i}},"getIntersectPoints"),P_e=o(function(t,e,r,n){let i=0;for(let a of e){i=i+1;let s=a.wrap&&Wt.wrap,l=I_e(Wt);n.db.getC4Type()==="C4Dynamic"&&(a.label.text=i+": "+a.label.text);let h=Zi(a.label.text,l);Ll("label",a,s,l,h),a.techn&&a.techn.text!==""&&(h=Zi(a.techn.text,l),Ll("techn",a,s,l,h)),a.descr&&a.descr.text!==""&&(h=Zi(a.descr.text,l),Ll("descr",a,s,l,h));let f=r(a.from),d=r(a.to),p=O_e(f,d);a.startPoint=p.startPoint,a.endPoint=p.endPoint}Al.drawRels(t,e,Wt)},"drawRels");o(LQ,"drawInsideBoundary");B_e=o(function(t,e,r,n){Wt=ge().c4;let i=ge().securityLevel,a;i==="sandbox"&&(a=qe("#i"+e));let s=i==="sandbox"?qe(a.nodes()[0].contentDocument.body):qe("body"),l=n.db;n.db.setWrap(Wt.wrap),AQ=l.getC4ShapeInRow(),WL=l.getC4BoundaryInRow(),X.debug(`C:${JSON.stringify(Wt,null,2)}`);let u=i==="sandbox"?s.select(`[id="${e}"]`):qe(`[id="${e}"]`);Al.insertComputerIcon(u),Al.insertDatabaseIcon(u),Al.insertClockIcon(u);let h=new IT(n);h.setData(Wt.diagramMarginX,Wt.diagramMarginX,Wt.diagramMarginY,Wt.diagramMarginY),h.data.widthLimit=screen.availWidth,NT=Wt.diagramMarginX,MT=Wt.diagramMarginY;let f=n.db.getTitle(),d=n.db.getBoundaries("");LQ(u,"",h,d,n),Al.insertArrowHead(u),Al.insertArrowEnd(u),Al.insertArrowCrossHead(u),Al.insertArrowFilledHead(u),P_e(u,n.db.getRels(),n.db.getC4Shape,n),h.data.stopx=NT,h.data.stopy=MT;let p=h.data,g=p.stopy-p.starty+2*Wt.diagramMarginY,v=p.stopx-p.startx+2*Wt.diagramMarginX;f&&u.append("text").text(f).attr("x",(p.stopx-p.startx)/2-4*Wt.diagramMarginX).attr("y",p.starty+Wt.diagramMarginY),mn(u,g,v,Wt.useMaxWidth);let x=f?60:0;u.attr("viewBox",p.startx-Wt.diagramMarginX+" -"+(Wt.diagramMarginY+x)+" "+v+" "+(g+x)),X.debug("models:",p)},"draw"),XL={drawPersonOrSystemArray:DQ,drawBoundary:_Q,setConf:YL,draw:B_e}});var F_e,NQ,MQ=M(()=>{"use strict";F_e=o(t=>`.person {
+ stroke: ${t.personBorder};
+ fill: ${t.personBkg};
+ }
+`,"getStyles"),NQ=F_e});var IQ={};dr(IQ,{diagram:()=>$_e});var $_e,OQ=M(()=>{"use strict";RA();GA();RQ();MQ();$_e={parser:sH,db:lv,renderer:XL,styles:NQ,init:o(({c4:t,wrap:e})=>{XL.setConf(t),lv.setWrap(e)},"init")}});function ZQ(t){return typeof t>"u"||t===null}function U_e(t){return typeof t=="object"&&t!==null}function H_e(t){return Array.isArray(t)?t:ZQ(t)?[]:[t]}function q_e(t,e){var r,n,i,a;if(e)for(a=Object.keys(e),r=0,n=a.length;r"u"&&Nu(t,e,null,!1,!1))&&(n!==""&&(n+=","+(t.condenseFlow?"":" ")),n+=t.dump);t.tag=i,t.dump="["+n+"]"}function KQ(t,e,r,n){var i="",a=t.tag,s,l,u;for(s=0,l=r.length;s tag resolver accepts not "'+u+'" style');t.dump=n}return!0}return!1}function Nu(t,e,r,n,i,a,s){t.tag=null,t.dump=r,QQ(t,r,!1)||QQ(t,r,!0);var l=dZ.call(t.dump),u=n,h;n&&(n=t.flowLevel<0||t.flowLevel>e);var f=l==="[object Object]"||l==="[object Array]",d,p;if(f&&(d=t.duplicates.indexOf(r),p=d!==-1),(t.tag!==null&&t.tag!=="?"||p||t.indent!==2&&e>0)&&(i=!1),p&&t.usedDuplicates[d])t.dump="*ref_"+d;else{if(f&&p&&!t.usedDuplicates[d]&&(t.usedDuplicates[d]=!0),l==="[object Object]")n&&Object.keys(t.dump).length!==0?(a9e(t,e,t.dump,i),p&&(t.dump="&ref_"+d+t.dump)):(i9e(t,e,t.dump),p&&(t.dump="&ref_"+d+" "+t.dump));else if(l==="[object Array]")n&&t.dump.length!==0?(t.noArrayIndent&&!s&&e>0?KQ(t,e-1,t.dump,i):KQ(t,e,t.dump,i),p&&(t.dump="&ref_"+d+t.dump)):(n9e(t,e,t.dump),p&&(t.dump="&ref_"+d+" "+t.dump));else if(l==="[object String]")t.tag!=="?"&&e9e(t,t.dump,e,a,u);else{if(l==="[object Undefined]")return!1;if(t.skipInvalid)return!1;throw new Is("unacceptable kind of an object to dump "+l)}t.tag!==null&&t.tag!=="?"&&(h=encodeURI(t.tag[0]==="!"?t.tag.slice(1):t.tag).replace(/!/g,"%21"),t.tag[0]==="!"?h="!"+h:h.slice(0,18)==="tag:yaml.org,2002:"?h="!!"+h.slice(18):h="!<"+h+">",t.dump=h+" "+t.dump)}return!0}function s9e(t,e){var r=[],n=[],i,a;for(r9(t,r,n),i=0,a=n.length;i{"use strict";o(ZQ,"isNothing");o(U_e,"isObject");o(H_e,"toArray");o(q_e,"extend");o(W_e,"repeat");o(Y_e,"isNegativeZero");X_e=ZQ,j_e=U_e,K_e=H_e,Q_e=W_e,Z_e=Y_e,J_e=q_e,Pi={isNothing:X_e,isObject:j_e,toArray:K_e,repeat:Q_e,isNegativeZero:Z_e,extend:J_e};o(JQ,"formatError");o(x2,"YAMLException$1");x2.prototype=Object.create(Error.prototype);x2.prototype.constructor=x2;x2.prototype.toString=o(function(e){return this.name+": "+JQ(this,e)},"toString");Is=x2;o(jL,"getLine");o(KL,"padStart");o(eDe,"makeSnippet");tDe=eDe,rDe=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],nDe=["scalar","sequence","mapping"];o(iDe,"compileStyleAliases");o(aDe,"Type$1");Ia=aDe;o(BQ,"compileList");o(sDe,"compileMap");o(ZL,"Schema$1");ZL.prototype.extend=o(function(e){var r=[],n=[];if(e instanceof Ia)n.push(e);else if(Array.isArray(e))n=n.concat(e);else if(e&&(Array.isArray(e.implicit)||Array.isArray(e.explicit)))e.implicit&&(r=r.concat(e.implicit)),e.explicit&&(n=n.concat(e.explicit));else throw new Is("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");r.forEach(function(a){if(!(a instanceof Ia))throw new Is("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(a.loadKind&&a.loadKind!=="scalar")throw new Is("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(a.multi)throw new Is("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),n.forEach(function(a){if(!(a instanceof Ia))throw new Is("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var i=Object.create(ZL.prototype);return i.implicit=(this.implicit||[]).concat(r),i.explicit=(this.explicit||[]).concat(n),i.compiledImplicit=BQ(i,"implicit"),i.compiledExplicit=BQ(i,"explicit"),i.compiledTypeMap=sDe(i.compiledImplicit,i.compiledExplicit),i},"extend");oDe=ZL,lDe=new Ia("tag:yaml.org,2002:str",{kind:"scalar",construct:o(function(t){return t!==null?t:""},"construct")}),cDe=new Ia("tag:yaml.org,2002:seq",{kind:"sequence",construct:o(function(t){return t!==null?t:[]},"construct")}),uDe=new Ia("tag:yaml.org,2002:map",{kind:"mapping",construct:o(function(t){return t!==null?t:{}},"construct")}),hDe=new oDe({explicit:[lDe,cDe,uDe]});o(fDe,"resolveYamlNull");o(dDe,"constructYamlNull");o(pDe,"isNull");mDe=new Ia("tag:yaml.org,2002:null",{kind:"scalar",resolve:fDe,construct:dDe,predicate:pDe,represent:{canonical:o(function(){return"~"},"canonical"),lowercase:o(function(){return"null"},"lowercase"),uppercase:o(function(){return"NULL"},"uppercase"),camelcase:o(function(){return"Null"},"camelcase"),empty:o(function(){return""},"empty")},defaultStyle:"lowercase"});o(gDe,"resolveYamlBoolean");o(yDe,"constructYamlBoolean");o(vDe,"isBoolean");xDe=new Ia("tag:yaml.org,2002:bool",{kind:"scalar",resolve:gDe,construct:yDe,predicate:vDe,represent:{lowercase:o(function(t){return t?"true":"false"},"lowercase"),uppercase:o(function(t){return t?"TRUE":"FALSE"},"uppercase"),camelcase:o(function(t){return t?"True":"False"},"camelcase")},defaultStyle:"lowercase"});o(bDe,"isHexCode");o(TDe,"isOctCode");o(wDe,"isDecCode");o(kDe,"resolveYamlInteger");o(EDe,"constructYamlInteger");o(SDe,"isInteger");CDe=new Ia("tag:yaml.org,2002:int",{kind:"scalar",resolve:kDe,construct:EDe,predicate:SDe,represent:{binary:o(function(t){return t>=0?"0b"+t.toString(2):"-0b"+t.toString(2).slice(1)},"binary"),octal:o(function(t){return t>=0?"0o"+t.toString(8):"-0o"+t.toString(8).slice(1)},"octal"),decimal:o(function(t){return t.toString(10)},"decimal"),hexadecimal:o(function(t){return t>=0?"0x"+t.toString(16).toUpperCase():"-0x"+t.toString(16).toUpperCase().slice(1)},"hexadecimal")},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),ADe=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");o(_De,"resolveYamlFloat");o(DDe,"constructYamlFloat");LDe=/^[-+]?[0-9]+e/;o(RDe,"representYamlFloat");o(NDe,"isFloat");MDe=new Ia("tag:yaml.org,2002:float",{kind:"scalar",resolve:_De,construct:DDe,predicate:NDe,represent:RDe,defaultStyle:"lowercase"}),eZ=hDe.extend({implicit:[mDe,xDe,CDe,MDe]}),IDe=eZ,tZ=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),rZ=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");o(ODe,"resolveYamlTimestamp");o(PDe,"constructYamlTimestamp");o(BDe,"representYamlTimestamp");FDe=new Ia("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:ODe,construct:PDe,instanceOf:Date,represent:BDe});o($De,"resolveYamlMerge");zDe=new Ia("tag:yaml.org,2002:merge",{kind:"scalar",resolve:$De}),n9=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
+\r`;o(GDe,"resolveYamlBinary");o(VDe,"constructYamlBinary");o(UDe,"representYamlBinary");o(HDe,"isBinary");qDe=new Ia("tag:yaml.org,2002:binary",{kind:"scalar",resolve:GDe,construct:VDe,predicate:HDe,represent:UDe}),WDe=Object.prototype.hasOwnProperty,YDe=Object.prototype.toString;o(XDe,"resolveYamlOmap");o(jDe,"constructYamlOmap");KDe=new Ia("tag:yaml.org,2002:omap",{kind:"sequence",resolve:XDe,construct:jDe}),QDe=Object.prototype.toString;o(ZDe,"resolveYamlPairs");o(JDe,"constructYamlPairs");eLe=new Ia("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:ZDe,construct:JDe}),tLe=Object.prototype.hasOwnProperty;o(rLe,"resolveYamlSet");o(nLe,"constructYamlSet");iLe=new Ia("tag:yaml.org,2002:set",{kind:"mapping",resolve:rLe,construct:nLe}),nZ=IDe.extend({implicit:[FDe,zDe],explicit:[qDe,KDe,eLe,iLe]}),Xh=Object.prototype.hasOwnProperty,OT=1,iZ=2,aZ=3,PT=4,QL=1,aLe=2,FQ=3,sLe=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,oLe=/[\x85\u2028\u2029]/,lLe=/[,\[\]\{\}]/,sZ=/^(?:!|!!|![a-z\-]+!)$/i,oZ=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;o($Q,"_class");o(bc,"is_EOL");o(Yd,"is_WHITE_SPACE");o(Os,"is_WS_OR_EOL");o(bm,"is_FLOW_INDICATOR");o(cLe,"fromHexCode");o(uLe,"escapedHexLen");o(hLe,"fromDecimalCode");o(zQ,"simpleEscapeSequence");o(fLe,"charFromCodepoint");lZ=new Array(256),cZ=new Array(256);for(Wd=0;Wd<256;Wd++)lZ[Wd]=zQ(Wd)?1:0,cZ[Wd]=zQ(Wd);o(dLe,"State$1");o(uZ,"generateError");o(Zt,"throwError");o(BT,"throwWarning");GQ={YAML:o(function(e,r,n){var i,a,s;e.version!==null&&Zt(e,"duplication of %YAML directive"),n.length!==1&&Zt(e,"YAML directive accepts exactly one argument"),i=/^([0-9]+)\.([0-9]+)$/.exec(n[0]),i===null&&Zt(e,"ill-formed argument of the YAML directive"),a=parseInt(i[1],10),s=parseInt(i[2],10),a!==1&&Zt(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=s<2,s!==1&&s!==2&&BT(e,"unsupported YAML version of the document")},"handleYamlDirective"),TAG:o(function(e,r,n){var i,a;n.length!==2&&Zt(e,"TAG directive accepts exactly two arguments"),i=n[0],a=n[1],sZ.test(i)||Zt(e,"ill-formed tag handle (first argument) of the TAG directive"),Xh.call(e.tagMap,i)&&Zt(e,'there is a previously declared suffix for "'+i+'" tag handle'),oZ.test(a)||Zt(e,"ill-formed tag prefix (second argument) of the TAG directive");try{a=decodeURIComponent(a)}catch{Zt(e,"tag prefix is malformed: "+a)}e.tagMap[i]=a},"handleTagDirective")};o(Yh,"captureSegment");o(VQ,"mergeMappings");o(Tm,"storeMappingPair");o(i9,"readLineBreak");o(Ci,"skipSeparationSpace");o(zT,"testDocumentSeparator");o(a9,"writeFoldedLines");o(pLe,"readPlainScalar");o(mLe,"readSingleQuotedScalar");o(gLe,"readDoubleQuotedScalar");o(yLe,"readFlowCollection");o(vLe,"readBlockScalar");o(UQ,"readBlockSequence");o(xLe,"readBlockMapping");o(bLe,"readTagProperty");o(TLe,"readAnchorProperty");o(wLe,"readAlias");o(wm,"composeNode");o(kLe,"readDocument");o(hZ,"loadDocuments");o(ELe,"loadAll$1");o(SLe,"load$1");CLe=ELe,ALe=SLe,fZ={loadAll:CLe,load:ALe},dZ=Object.prototype.toString,pZ=Object.prototype.hasOwnProperty,s9=65279,_Le=9,b2=10,DLe=13,LLe=32,RLe=33,NLe=34,JL=35,MLe=37,ILe=38,OLe=39,PLe=42,mZ=44,BLe=45,FT=58,FLe=61,$Le=62,zLe=63,GLe=64,gZ=91,yZ=93,VLe=96,vZ=123,ULe=124,xZ=125,Oa={};Oa[0]="\\0";Oa[7]="\\a";Oa[8]="\\b";Oa[9]="\\t";Oa[10]="\\n";Oa[11]="\\v";Oa[12]="\\f";Oa[13]="\\r";Oa[27]="\\e";Oa[34]='\\"';Oa[92]="\\\\";Oa[133]="\\N";Oa[160]="\\_";Oa[8232]="\\L";Oa[8233]="\\P";HLe=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],qLe=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;o(WLe,"compileStyleMap");o(YLe,"encodeHex");XLe=1,T2=2;o(jLe,"State");o(HQ,"indentString");o(e9,"generateNextLine");o(KLe,"testImplicitResolving");o($T,"isWhitespace");o(w2,"isPrintable");o(qQ,"isNsCharOrWhitespace");o(WQ,"isPlainSafe");o(QLe,"isPlainSafeFirst");o(ZLe,"isPlainSafeLast");o(v2,"codePointAt");o(bZ,"needIndentIndicator");TZ=1,t9=2,wZ=3,kZ=4,xm=5;o(JLe,"chooseScalarStyle");o(e9e,"writeScalar");o(YQ,"blockHeader");o(XQ,"dropEndingNewline");o(t9e,"foldString");o(jQ,"foldLine");o(r9e,"escapeString");o(n9e,"writeFlowSequence");o(KQ,"writeBlockSequence");o(i9e,"writeFlowMapping");o(a9e,"writeBlockMapping");o(QQ,"detectType");o(Nu,"writeNode");o(s9e,"getDuplicateReferences");o(r9,"inspectNode");o(o9e,"dump$1");l9e=o9e,c9e={dump:l9e};o(o9,"renamed");jh=eZ,Kh=fZ.load,N6t=fZ.loadAll,M6t=c9e.dump,I6t=o9("safeLoad","load"),O6t=o9("safeLoadAll","loadAll"),P6t=o9("safeDump","dump")});function h9(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function DZ(t){jd=t}function on(t,e=""){let r=typeof t=="string"?t:t.source,n={replace:o((i,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(as.caret,"$1"),r=r.replace(i,s),n},"replace"),getRegex:o(()=>new RegExp(r,e),"getRegex")};return n}function Tc(t,e){if(e){if(as.escapeTest.test(t))return t.replace(as.escapeReplace,SZ)}else if(as.escapeTestNoEncode.test(t))return t.replace(as.escapeReplaceNoEncode,SZ);return t}function CZ(t){try{t=encodeURI(t).replace(as.percentDecode,"%")}catch{return null}return t}function AZ(t,e){let r=t.replace(as.findPipe,(a,s,l)=>{let u=!1,h=s;for(;--h>=0&&l[h]==="\\";)u=!u;return u?"|":" |"}),n=r.split(as.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length
+`:"'+(r?i:Tc(i,!0))+`
+`}blockquote({tokens:t}){return`"+(r?i:Tc(i,!0))+`
+${this.parser.parse(t)}
+`}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`
+`}list(t){let e=t.ordered,r=t.start,n="";for(let s=0;s
+
+`+e+`
+`+n+`
+`}tablerow({text:t}){return`
+${t}
+`}tablecell(t){let e=this.parser.parseInline(t.tokens),r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+e+`${r}>
+`}strong({tokens:t}){return`${this.parser.parseInline(t)}`}em({tokens:t}){return`${this.parser.parseInline(t)}`}codespan({text:t}){return`${Tc(t,!0)}`}br(t){return"
"}del({tokens:t}){return`${this.parser.parseInline(t)}`}link({href:t,title:e,tokens:r}){let n=this.parser.parseInline(r),i=CZ(t);if(i===null)return n;t=i;let a='"+n+"",a}image({href:t,title:e,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let i=CZ(t);if(i===null)return Tc(r);t=i;let a=`",a}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:Tc(t.text)}},x9=class{static{o(this,"$")}strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}},Iu=class u9{static{o(this,"l")}options;renderer;textRenderer;constructor(e){this.options=e||jd,this.options.renderer=this.options.renderer||new qT,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new x9}static parse(e,r){return new u9(r).parse(e)}static parseInline(e,r){return new u9(r).parseInline(e)}parse(e,r=!0){let n="";for(let i=0;i
"+Tc(r.message+"",!0)+"
";return e?Promise.resolve(n):n}if(e)return Promise.reject(r);throw r}}},Xd=new q9e;o(nn,"d");nn.options=nn.setOptions=function(t){return Xd.setOptions(t),nn.defaults=Xd.defaults,DZ(nn.defaults),nn};nn.getDefaults=h9;nn.defaults=jd;nn.use=function(...t){return Xd.use(...t),nn.defaults=Xd.defaults,DZ(nn.defaults),nn};nn.walkTokens=function(t,e){return Xd.walkTokens(t,e)};nn.parseInline=Xd.parseInline;nn.Parser=Iu;nn.parser=Iu.parse;nn.Renderer=qT;nn.TextRenderer=x9;nn.Lexer=Mu;nn.lexer=Mu.lex;nn.Tokenizer=HT;nn.Hooks=C2;nn.parse=nn;F6t=nn.options,$6t=nn.setOptions,z6t=nn.use,G6t=nn.walkTokens,V6t=nn.parseInline,U6t=Iu.parse,H6t=Mu.lex});function W9e(t,{markdownAutoWrap:e}){let n=t.replace(/
/g,`
+`).replace(/\n{2,}/g,`
+`),i=B3(n);return e===!1?i.replace(/ /g," "):i}function GZ(t,e={}){let r=W9e(t,e),n=nn.lexer(r),i=[[]],a=0;function s(l,u="normal"){l.type==="text"?l.text.split(`
+`).forEach((f,d)=>{d!==0&&(a++,i.push([])),f.split(" ").forEach(p=>{p=p.replace(/'/g,"'"),p&&i[a].push({content:p,type:u})})}):l.type==="strong"||l.type==="em"?l.tokens.forEach(h=>{s(h,l.type)}):l.type==="html"&&i[a].push({content:l.text,type:"normal"})}return o(s,"processNode"),n.forEach(l=>{l.type==="paragraph"?l.tokens?.forEach(u=>{s(u)}):l.type==="html"?i[a].push({content:l.text,type:"normal"}):i[a].push({content:l.raw,type:"normal"})}),i}function VZ(t,{markdownAutoWrap:e}={}){let r=nn.lexer(t);function n(i){return i.type==="text"?e===!1?i.text.replace(/\n */g,"
").replace(/ /g," "):i.text.replace(/\n */g,"
"):i.type==="strong"?`${i.tokens?.map(n).join("")}`:i.type==="em"?`${i.tokens?.map(n).join("")}`:i.type==="paragraph"?`
/g,"
"),d=GZ(f.replace("
","
"),h),p=Q9e(l,t,d,e?u:!1);if(s){/stroke:/.exec(r)&&(r=r.replace("stroke:","lineColor:"));let m=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/color:/g,"fill:");qe(p).attr("style",m)}else{let m=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/background:/g,"fill:");qe(p).select("rect").attr("style",m.replace(/background:/g,"fill:"));let g=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/color:/g,"fill:");qe(p).select("text").attr("style",g)}return p}},"createText")});function Vt(t){let e=t.map((r,n)=>`${n===0?"M":"L"}${r.x},${r.y}`);return e.push("Z"),e.join(" ")}function Go(t,e,r,n,i,a){let s=[],u=r-t,h=n-e,f=u/a,d=2*Math.PI/f,p=e+h/2;for(let m=0;m<=50;m++){let g=m/50,y=t+g*u,v=p+i*Math.sin(d*(y-t));s.push({x:y,y:v})}return s}function Kd(t,e,r,n,i,a){let s=[],l=i*Math.PI/180,f=(a*Math.PI/180-l)/(n-1);for(let d=0;d]*>/g,"").trim()==="";await Promise.all([...m].map(y=>new Promise(v=>{function x(){if(y.style.display="flex",y.style.flexDirection="column",g){let b=ge().fontSize?ge().fontSize:window.getComputedStyle(document.body).fontSize,T=5,[S=ur.fontSize]=vc(b),w=S*T+"px";y.style.minWidth=w,y.style.maxWidth=w}else y.style.width="100%";v(y)}o(x,"setupImage"),setTimeout(()=>{y.complete&&x()}),y.addEventListener("error",x),y.addEventListener("load",x)})))}h=d.getBoundingClientRect(),p.attr("width",h.width),p.attr("height",h.height)}return i?s.attr("transform","translate("+-h.width/2+", "+-h.height/2+")"):s.attr("transform","translate(0, "+-h.height/2+")"),e.centerLabel&&s.attr("transform","translate("+-h.width/2+", "+-h.height/2+")"),s.insert("rect",":first-child"),{shapeSvg:a,bbox:h,halfPadding:f,label:s}},"labelHelper"),XT=o(async(t,e,r)=>{let n=r.useHtmlLabels||vr(ge()?.flowchart?.htmlLabels),i=t.insert("g").attr("class","label").attr("style",r.labelStyle||""),a=await di(i,sr(Ji(e),ge()),{useHtmlLabels:n,width:r.width||ge()?.flowchart?.wrappingWidth,style:r.labelStyle,addSvgBackground:!!r.icon||!!r.img}),s=a.getBBox(),l=r.padding/2;if(vr(ge()?.flowchart?.htmlLabels)){let u=a.children[0],h=qe(a);s=u.getBoundingClientRect(),h.attr("width",s.width),h.attr("height",s.height)}return n?i.attr("transform","translate("+-s.width/2+", "+-s.height/2+")"):i.attr("transform","translate(0, "+-s.height/2+")"),r.centerLabel&&i.attr("transform","translate("+-s.width/2+", "+-s.height/2+")"),i.insert("rect",":first-child"),{shapeSvg:t,bbox:s,halfPadding:l,label:i}},"insertLabel"),Qe=o((t,e)=>{let r=e.node().getBBox();t.width=r.width,t.height=r.height},"updateNodeBounds"),st=o((t,e)=>(t.look==="handDrawn"?"rough-node":"node")+" "+t.cssClasses+" "+(e||""),"getNodeClasses");o(Vt,"createPathFromPoints");o(Go,"generateFullSineWavePoints");o(Kd,"generateCirclePoints")});function Z9e(t,e){return t.intersect(e)}var jZ,KZ=M(()=>{"use strict";o(Z9e,"intersectNode");jZ=Z9e});function J9e(t,e,r,n){var i=t.x,a=t.y,s=i-n.x,l=a-n.y,u=Math.sqrt(e*e*l*l+r*r*s*s),h=Math.abs(e*r*s/u);n.x{"use strict";o(J9e,"intersectEllipse");jT=J9e});function eRe(t,e,r){return jT(t,e,e,r)}var QZ,ZZ=M(()=>{"use strict";E9();o(eRe,"intersectCircle");QZ=eRe});function tRe(t,e,r,n){{let i=e.y-t.y,a=t.x-e.x,s=e.x*t.y-t.x*e.y,l=i*r.x+a*r.y+s,u=i*n.x+a*n.y+s,h=1e-6;if(l!==0&&u!==0&&JZ(l,u))return;let f=n.y-r.y,d=r.x-n.x,p=n.x*r.y-r.x*n.y,m=f*t.x+d*t.y+p,g=f*e.x+d*e.y+p;if(Math.abs(m)
"),X.info("vertexText"+i);let a={isNode:n,label:Ji(i).replace(/fa[blrs]?:fa-[\w-]+/g,l=>``),labelStyle:e&&e.replace("fill:","color:")};return await kRe(a)}else{let a=document.createElementNS("http://www.w3.org/2000/svg","text");a.setAttribute("style",e.replace("color:","fill:"));let s=[];typeof i=="string"?s=i.split(/\\n|\n|
/gi):Array.isArray(i)?s=i:s=[];for(let l of s){let u=document.createElementNS("http://www.w3.org/2000/svg","tspan");u.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),u.setAttribute("dy","1em"),u.setAttribute("x","0"),r?u.setAttribute("class","title-row"):u.setAttribute("class","row"),u.textContent=l.trim(),a.appendChild(u)}return a}},"createLabel"),kc=ERe});async function Pee(t,e){let{labelStyles:r,nodeStyles:n}=je(e);e.labelStyle=r;let i;e.cssClasses?i="node "+e.cssClasses:i="node default";let a=t.insert("g").attr("class",i).attr("id",e.domId||e.id),s=a.insert("g"),l=a.insert("g").attr("class","label").attr("style",n),u=e.description,h=e.label,f=l.node().appendChild(await kc(h,e.labelStyle,!0,!0)),d={width:0,height:0};if(vr(ge()?.flowchart?.htmlLabels)){let A=f.children[0],L=qe(f);d=A.getBoundingClientRect(),L.attr("width",d.width),L.attr("height",d.height)}X.info("Text 2",u);let p=u||[],m=f.getBBox(),g=l.node().appendChild(await kc(p.join?p.join("
"):p,e.labelStyle,!0,!0)),y=g.children[0],v=qe(g);d=y.getBoundingClientRect(),v.attr("width",d.width),v.attr("height",d.height);let x=(e.padding||0)/2;qe(g).attr("transform","translate( "+(d.width>m.width?0:(m.width-d.width)/2)+", "+(m.height+x+5)+")"),qe(f).attr("transform","translate( "+(d.width
").length,d.innerHTML.includes("")&&(f+=d.innerHTML.split("]*>/g,"").trim()==="";await Promise.all([...m].map(y=>new Promise(v=>{function x(){if(y.style.display="flex",y.style.flexDirection="column",g){let b=a.fontSize?.toString()??window.getComputedStyle(document.body).fontSize,S=parseInt(b,10)*5+"px";y.style.minWidth=S,y.style.maxWidth=S}else y.style.width="100%";v(y)}o(x,"setupImage"),setTimeout(()=>{y.complete&&x()}),y.addEventListener("error",x),y.addEventListener("load",x)})))}h=d.getBoundingClientRect(),p.attr("width",h.width),p.attr("height",h.height)}else{n.includes("font-weight: bolder")&&qe(u).selectAll("tspan").attr("font-weight",""),f=u.children.length;let d=u.children[0];(u.textContent===""||u.textContent.includes(">"))&&(d.textContent=l[0]+l.substring(1).replaceAll(">",">").replaceAll("<","<").trim(),l[1]===" "&&(d.textContent=d.textContent[0]+" "+d.textContent.substring(1))),d.textContent==="undefined"&&(d.textContent=""),h=u.getBBox()}return i.attr("transform","translate(0,"+(-h.height/(2*f)+r)+")"),h.height}var Ete=M(()=>{"use strict";yr();qn();It();tr();Xt();zo();gr();o(kte,"textHelper");o(lw,"addText")});async function Ste(t,e){let r=ge(),n=r.class.padding??12,i=n,a=e.useHtmlLabels??vr(r.htmlLabels)??!0,s=e;s.annotations=s.annotations??[],s.members=s.members??[],s.methods=s.methods??[];let{shapeSvg:l,bbox:u}=await kte(t,e,r,a,i),{labelStyles:h,nodeStyles:f}=je(e);e.labelStyle=h,e.cssStyles=s.styles||"";let d=s.styles?.join(";")||f||"";e.cssStyles||(e.cssStyles=d.replaceAll("!important","").split(";"));let p=s.members.length===0&&s.methods.length===0&&!r.class?.hideEmptyMembersBox,m=Ze.svg(l),g=Je(e,{});e.look!=="handDrawn"&&(g.roughness=0,g.fillStyle="solid");let y=u.width,v=u.height;s.members.length===0&&s.methods.length===0?v+=i:s.members.length>0&&s.methods.length===0&&(v+=i*2);let x=-y/2,b=-v/2,T=m.rectangle(x-n,b-n-(p?n:s.members.length===0&&s.methods.length===0?-n/2:0),y+2*n,v+2*n+(p?n*2:s.members.length===0&&s.methods.length===0?-n:0),g),S=l.insert(()=>T,":first-child");S.attr("class","basic label-container");let w=S.node().getBBox();l.selectAll(".text").each((L,I,R)=>{let E=qe(R[I]),_=E.attr("transform"),D=0;if(_){let B=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(_);B&&(D=parseFloat(B[2]))}let O=D+b+n-(p?n:s.members.length===0&&s.methods.length===0?-n/2:0);a||(O-=4);let N=x;(E.attr("class").includes("label-group")||E.attr("class").includes("annotation-group"))&&(N=-E.node()?.getBBox().width/2||0,l.selectAll("text").each(function(P,B,F){window.getComputedStyle(F[B]).textAnchor==="middle"&&(N=0)})),E.attr("transform",`translate(${N}, ${O})`)});let k=l.select(".annotation-group").node().getBBox().height-(p?n/2:0)||0,C=l.select(".label-group").node().getBBox().height-(p?n/2:0)||0,A=l.select(".members-group").node().getBBox().height-(p?n/2:0)||0;if(s.members.length>0||s.methods.length>0||p){let L=m.line(w.x,k+C+b+n,w.x+w.width,k+C+b+n,g);l.insert(()=>L).attr("class","divider").attr("style",d)}if(p||s.members.length>0||s.methods.length>0){let L=m.line(w.x,k+C+A+b+i*2+n,w.x+w.width,k+C+A+b+n+i*2,g);l.insert(()=>L).attr("class","divider").attr("style",d)}if(s.look!=="handDrawn"&&l.selectAll("path").attr("style",d),S.select(":nth-child(2)").attr("style",d),l.selectAll(".divider").select("path").attr("style",d),e.labelStyle?l.selectAll("span").attr("style",e.labelStyle):l.selectAll("span").attr("style",d),!a){let L=RegExp(/color\s*:\s*([^;]*)/),I=L.exec(d);if(I){let R=I[0].replace("color","fill");l.selectAll("tspan").attr("style",R)}else if(h){let R=L.exec(h);if(R){let E=R[0].replace("color","fill");l.selectAll("tspan").attr("style",E)}}}return Qe(e,S),e.intersect=function(L){return Xe.rect(e,L)},l}var Cte=M(()=>{"use strict";It();Xt();yr();Ht();$t();Ut();Ete();gr();o(Ste,"classBox")});async function Ate(t,e){let{labelStyles:r,nodeStyles:n}=je(e);e.labelStyle=r;let i=e,a=e,s=20,l=20,u="verifyMethod"in e,h=st(e),f=t.insert("g").attr("class",h).attr("id",e.domId??e.id),d;u?d=await Ou(f,`<<${i.type}>>`,0,e.labelStyle):d=await Ou(f,"<<Element>>",0,e.labelStyle);let p=d,m=await Ou(f,i.name,p,e.labelStyle+"; font-weight: bold;");if(p+=m+l,u){let k=await Ou(f,`${i.requirementId?`ID: ${i.requirementId}`:""}`,p,e.labelStyle);p+=k;let C=await Ou(f,`${i.text?`Text: ${i.text}`:""}`,p,e.labelStyle);p+=C;let A=await Ou(f,`${i.risk?`Risk: ${i.risk}`:""}`,p,e.labelStyle);p+=A,await Ou(f,`${i.verifyMethod?`Verification: ${i.verifyMethod}`:""}`,p,e.labelStyle)}else{let k=await Ou(f,`${a.type?`Type: ${a.type}`:""}`,p,e.labelStyle);p+=k,await Ou(f,`${a.docRef?`Doc Ref: ${a.docRef}`:""}`,p,e.labelStyle)}let g=(f.node()?.getBBox().width??200)+s,y=(f.node()?.getBBox().height??200)+s,v=-g/2,x=-y/2,b=Ze.svg(f),T=Je(e,{});e.look!=="handDrawn"&&(T.roughness=0,T.fillStyle="solid");let S=b.rectangle(v,x,g,y,T),w=f.insert(()=>S,":first-child");if(w.attr("class","basic label-container").attr("style",n),f.selectAll(".label").each((k,C,A)=>{let L=qe(A[C]),I=L.attr("transform"),R=0,E=0;if(I){let N=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(I);N&&(R=parseFloat(N[1]),E=parseFloat(N[2]))}let _=E-y/2,D=v+s/2;(C===0||C===1)&&(D=R),L.attr("transform",`translate(${D}, ${_+s})`)}),p>d+m+l){let k=b.line(v,x+d+m+l,v+g,x+d+m+l,T);f.insert(()=>k).attr("style",n)}return Qe(e,w),e.intersect=function(k){return Xe.rect(e,k)},f}async function Ou(t,e,r,n=""){if(e==="")return 0;let i=t.insert("g").attr("class","label").attr("style",n),a=ge(),s=a.htmlLabels??!0,l=await di(i,av(Ji(e)),{width:Zi(e,a)+50,classes:"markdown-node-label",useHtmlLabels:s,style:n},a),u;if(s){let h=l.children[0],f=qe(l);u=h.getBoundingClientRect(),f.attr("width",u.width),f.attr("height",u.height)}else{let h=l.children[0];for(let f of h.children)f.textContent=f.textContent.replaceAll(">",">").replaceAll("<","<"),n&&f.setAttribute("style",n);u=l.getBBox(),u.height+=6}return i.attr("transform",`translate(${-u.width/2},${-u.height/2+r})`),u.height}var _te=M(()=>{"use strict";It();Ut();$t();Ht();tr();Xt();zo();yr();o(Ate,"requirementBox");o(Ou,"addText")});async function Dte(t,e,{config:r}){let{labelStyles:n,nodeStyles:i}=je(e);e.labelStyle=n||"";let a=10,s=e.width;e.width=(e.width??200)-10;let{shapeSvg:l,bbox:u,label:h}=await ut(t,e,st(e)),f=e.padding||10,d="",p;"ticket"in e&&e.ticket&&r?.kanban?.ticketBaseUrl&&(d=r?.kanban?.ticketBaseUrl.replace("#TICKET#",e.ticket),p=l.insert("svg:a",":first-child").attr("class","kanban-ticket-link").attr("xlink:href",d).attr("target","_blank"));let m={useHtmlLabels:e.useHtmlLabels,labelStyle:e.labelStyle||"",width:e.width,img:e.img,padding:e.padding||8,centerLabel:!1},g,y;p?{label:g,bbox:y}=await XT(p,"ticket"in e&&e.ticket||"",m):{label:g,bbox:y}=await XT(l,"ticket"in e&&e.ticket||"",m);let{label:v,bbox:x}=await XT(l,"assigned"in e&&e.assigned||"",m);e.width=s;let b=10,T=e?.width||0,S=Math.max(y.height,x.height)/2,w=Math.max(u.height+b*2,e?.height||0)+S,k=-T/2,C=-w/2;h.attr("transform","translate("+(f-T/2)+", "+(-S-u.height/2)+")"),g.attr("transform","translate("+(f-T/2)+", "+(-S+u.height/2)+")"),v.attr("transform","translate("+(f+T/2-x.width-2*a)+", "+(-S+u.height/2)+")");let A,{rx:L,ry:I}=e,{cssStyles:R}=e;if(e.look==="handDrawn"){let E=Ze.svg(l),_=Je(e,{}),D=L||I?E.path(Fs(k,C,T,w,L||0),_):E.rectangle(k,C,T,w,_);A=l.insert(()=>D,":first-child"),A.attr("class","basic label-container").attr("style",R||null)}else{A=l.insert("rect",":first-child"),A.attr("class","basic label-container __APA__").attr("style",i).attr("rx",L??5).attr("ry",I??5).attr("x",k).attr("y",C).attr("width",T).attr("height",w);let E="priority"in e&&e.priority;if(E){let _=l.append("line"),D=k+2,O=C+Math.floor((L??0)/2),N=C+w-Math.floor((L??0)/2);_.attr("x1",D).attr("y1",O).attr("x2",D).attr("y2",N).attr("stroke-width","4").attr("stroke",_Re(E))}}return Qe(e,A),e.height=w,e.intersect=function(E){return Xe.rect(e,E)},l}var _Re,Lte=M(()=>{"use strict";It();Ut();Zd();$t();Ht();_Re=o(t=>{switch(t){case"Very High":return"red";case"High":return"orange";case"Medium":return null;case"Low":return"blue";case"Very Low":return"lightblue"}},"colorFromPriority");o(Dte,"kanbanItem")});async function Rte(t,e){let{labelStyles:r,nodeStyles:n}=je(e);e.labelStyle=r;let{shapeSvg:i,bbox:a,halfPadding:s,label:l}=await ut(t,e,st(e)),u=a.width+10*s,h=a.height+8*s,f=.15*u,{cssStyles:d}=e,p=a.width+20,m=a.height+20,g=Math.max(u,p),y=Math.max(h,m);l.attr("transform",`translate(${-a.width/2}, ${-a.height/2})`);let v,x=`M0 0
+ a${f},${f} 1 0,0 ${g*.25},${-1*y*.1}
+ a${f},${f} 1 0,0 ${g*.25},0
+ a${f},${f} 1 0,0 ${g*.25},0
+ a${f},${f} 1 0,0 ${g*.25},${y*.1}
+
+ a${f},${f} 1 0,0 ${g*.15},${y*.33}
+ a${f*.8},${f*.8} 1 0,0 0,${y*.34}
+ a${f},${f} 1 0,0 ${-1*g*.15},${y*.33}
+
+ a${f},${f} 1 0,0 ${-1*g*.25},${y*.15}
+ a${f},${f} 1 0,0 ${-1*g*.25},0
+ a${f},${f} 1 0,0 ${-1*g*.25},0
+ a${f},${f} 1 0,0 ${-1*g*.25},${-1*y*.15}
+
+ a${f},${f} 1 0,0 ${-1*g*.1},${-1*y*.33}
+ a${f*.8},${f*.8} 1 0,0 0,${-1*y*.34}
+ a${f},${f} 1 0,0 ${g*.1},${-1*y*.33}
+ H0 V0 Z`;if(e.look==="handDrawn"){let b=Ze.svg(i),T=Je(e,{}),S=b.path(x,T);v=i.insert(()=>S,":first-child"),v.attr("class","basic label-container").attr("style",Cn(d))}else v=i.insert("path",":first-child").attr("class","basic label-container").attr("style",n).attr("d",x);return v.attr("transform",`translate(${-g/2}, ${-y/2})`),Qe(e,v),e.calcIntersect=function(b,T){return Xe.rect(b,T)},e.intersect=function(b){return X.info("Bang intersect",e,b),Xe.rect(e,b)},i}var Nte=M(()=>{"use strict";pt();It();Ut();$t();Ht();tr();o(Rte,"bang")});async function Mte(t,e){let{labelStyles:r,nodeStyles:n}=je(e);e.labelStyle=r;let{shapeSvg:i,bbox:a,halfPadding:s,label:l}=await ut(t,e,st(e)),u=a.width+2*s,h=a.height+2*s,f=.15*u,d=.25*u,p=.35*u,m=.2*u,{cssStyles:g}=e,y,v=`M0 0
+ a${f},${f} 0 0,1 ${u*.25},${-1*u*.1}
+ a${p},${p} 1 0,1 ${u*.4},${-1*u*.1}
+ a${d},${d} 1 0,1 ${u*.35},${u*.2}
+
+ a${f},${f} 1 0,1 ${u*.15},${h*.35}
+ a${m},${m} 1 0,1 ${-1*u*.15},${h*.65}
+
+ a${d},${f} 1 0,1 ${-1*u*.25},${u*.15}
+ a${p},${p} 1 0,1 ${-1*u*.5},0
+ a${f},${f} 1 0,1 ${-1*u*.25},${-1*u*.15}
+
+ a${f},${f} 1 0,1 ${-1*u*.1},${-1*h*.35}
+ a${m},${m} 1 0,1 ${u*.1},${-1*h*.65}
+ H0 V0 Z`;if(e.look==="handDrawn"){let x=Ze.svg(i),b=Je(e,{}),T=x.path(v,b);y=i.insert(()=>T,":first-child"),y.attr("class","basic label-container").attr("style",Cn(g))}else y=i.insert("path",":first-child").attr("class","basic label-container").attr("style",n).attr("d",v);return l.attr("transform",`translate(${-a.width/2}, ${-a.height/2})`),y.attr("transform",`translate(${-u/2}, ${-h/2})`),Qe(e,y),e.calcIntersect=function(x,b){return Xe.rect(x,b)},e.intersect=function(x){return X.info("Cloud intersect",e,x),Xe.rect(e,x)},i}var Ite=M(()=>{"use strict";Ht();pt();tr();Ut();$t();It();o(Mte,"cloud")});async function Ote(t,e){let{labelStyles:r,nodeStyles:n}=je(e);e.labelStyle=r;let{shapeSvg:i,bbox:a,halfPadding:s,label:l}=await ut(t,e,st(e)),u=a.width+8*s,h=a.height+2*s,f=5,d=`
+ M${-u/2} ${h/2-f}
+ v${-h+2*f}
+ q0,-${f} ${f},-${f}
+ h${u-2*f}
+ q${f},0 ${f},${f}
+ v${h-2*f}
+ q0,${f} -${f},${f}
+ h${-u+2*f}
+ q-${f},0 -${f},-${f}
+ Z
+ `,p=i.append("path").attr("id","node-"+e.id).attr("class","node-bkg node-"+e.type).attr("style",n).attr("d",d);return i.append("line").attr("class","node-line-").attr("x1",-u/2).attr("y1",h/2).attr("x2",u/2).attr("y2",h/2),l.attr("transform",`translate(${-a.width/2}, ${-a.height/2})`),i.append(()=>l.node()),Qe(e,p),e.calcIntersect=function(m,g){return Xe.rect(m,g)},e.intersect=function(m){return Xe.rect(e,m)},i}var Pte=M(()=>{"use strict";Ut();$t();It();o(Ote,"defaultMindmapNode")});async function Bte(t,e){let r={padding:e.padding??0};return aw(t,e,r)}var Fte=M(()=>{"use strict";U9();o(Bte,"mindmapCircle")});function $te(t){return t in q9}var DRe,LRe,q9,W9=M(()=>{"use strict";bJ();kJ();SJ();AJ();U9();DJ();RJ();MJ();OJ();BJ();$J();GJ();UJ();qJ();YJ();jJ();QJ();JJ();tee();nee();aee();oee();cee();hee();dee();mee();yee();xee();Tee();kee();See();Aee();Dee();Ree();Mee();Oee();Bee();$ee();Gee();Uee();qee();Yee();jee();Qee();Jee();tte();nte();ate();ote();cte();hte();dte();mte();yte();xte();Tte();wte();Cte();_te();Lte();Nte();Ite();Pte();Fte();DRe=[{semanticName:"Process",name:"Rectangle",shortName:"rect",description:"Standard process shape",aliases:["proc","process","rectangle"],internalAliases:["squareRect"],handler:Hee},{semanticName:"Event",name:"Rounded Rectangle",shortName:"rounded",description:"Represents an event",aliases:["event"],internalAliases:["roundedRect"],handler:Fee},{semanticName:"Terminal Point",name:"Stadium",shortName:"stadium",description:"Terminal point",aliases:["terminal","pill"],handler:Wee},{semanticName:"Subprocess",name:"Framed Rectangle",shortName:"fr-rect",description:"Subprocess",aliases:["subprocess","subproc","framed-rectangle","subroutine"],handler:ete},{semanticName:"Database",name:"Cylinder",shortName:"cyl",description:"Database storage",aliases:["db","database","cylinder"],handler:FJ},{semanticName:"Start",name:"Circle",shortName:"circle",description:"Starting point",aliases:["circ"],handler:aw},{semanticName:"Bang",name:"Bang",shortName:"bang",description:"Bang",aliases:["bang"],handler:Rte},{semanticName:"Cloud",name:"Cloud",shortName:"cloud",description:"cloud",aliases:["cloud"],handler:Mte},{semanticName:"Decision",name:"Diamond",shortName:"diam",description:"Decision-making step",aliases:["decision","diamond","question"],handler:Nee},{semanticName:"Prepare Conditional",name:"Hexagon",shortName:"hex",description:"Preparation or condition step",aliases:["hexagon","prepare"],handler:ZJ},{semanticName:"Data Input/Output",name:"Lean Right",shortName:"lean-r",description:"Represents input or output",aliases:["lean-right","in-out"],internalAliases:["lean_right"],handler:vee},{semanticName:"Data Input/Output",name:"Lean Left",shortName:"lean-l",description:"Represents output or input",aliases:["lean-left","out-in"],internalAliases:["lean_left"],handler:gee},{semanticName:"Priority Action",name:"Trapezoid Base Bottom",shortName:"trap-b",description:"Priority action",aliases:["priority","trapezoid-bottom","trapezoid"],handler:ute},{semanticName:"Manual Operation",name:"Trapezoid Base Top",shortName:"trap-t",description:"Represents a manual task",aliases:["manual","trapezoid-top","inv-trapezoid"],internalAliases:["inv_trapezoid"],handler:fee},{semanticName:"Stop",name:"Double Circle",shortName:"dbl-circ",description:"Represents a stop point",aliases:["double-circle"],internalAliases:["doublecircle"],handler:VJ},{semanticName:"Text Block",name:"Text Block",shortName:"text",description:"Text block",handler:ste},{semanticName:"Card",name:"Notched Rectangle",shortName:"notch-rect",description:"Represents a card",aliases:["card","notched-rectangle"],handler:EJ},{semanticName:"Lined/Shaded Process",name:"Lined Rectangle",shortName:"lin-rect",description:"Lined process shape",aliases:["lined-rectangle","lined-process","lin-proc","shaded-process"],handler:zee},{semanticName:"Start",name:"Small Circle",shortName:"sm-circ",description:"Small starting point",aliases:["start","small-circle"],internalAliases:["stateStart"],handler:Zee},{semanticName:"Stop",name:"Framed Circle",shortName:"fr-circ",description:"Stop point",aliases:["stop","framed-circle"],internalAliases:["stateEnd"],handler:Kee},{semanticName:"Fork/Join",name:"Filled Rectangle",shortName:"fork",description:"Fork or join in process flow",aliases:["join"],internalAliases:["forkJoin"],handler:XJ},{semanticName:"Collate",name:"Hourglass",shortName:"hourglass",description:"Represents a collate operation",aliases:["hourglass","collate"],handler:eee},{semanticName:"Comment",name:"Curly Brace",shortName:"brace",description:"Adds a comment",aliases:["comment","brace-l"],handler:LJ},{semanticName:"Comment Right",name:"Curly Brace",shortName:"brace-r",description:"Adds a comment",handler:NJ},{semanticName:"Comment with braces on both sides",name:"Curly Braces",shortName:"braces",description:"Adds a comment",handler:IJ},{semanticName:"Com Link",name:"Lightning Bolt",shortName:"bolt",description:"Communication link",aliases:["com-link","lightning-bolt"],handler:bee},{semanticName:"Document",name:"Document",shortName:"doc",description:"Represents a document",aliases:["doc","document"],handler:gte},{semanticName:"Delay",name:"Half-Rounded Rectangle",shortName:"delay",description:"Represents a delay",aliases:["half-rounded-rectangle"],handler:KJ},{semanticName:"Direct Access Storage",name:"Horizontal Cylinder",shortName:"h-cyl",description:"Direct access storage",aliases:["das","horizontal-cylinder"],handler:lte},{semanticName:"Disk Storage",name:"Lined Cylinder",shortName:"lin-cyl",description:"Disk storage",aliases:["disk","lined-cylinder"],handler:wee},{semanticName:"Display",name:"Curved Trapezoid",shortName:"curv-trap",description:"Represents a display",aliases:["curved-trapezoid","display"],handler:PJ},{semanticName:"Divided Process",name:"Divided Rectangle",shortName:"div-rect",description:"Divided process shape",aliases:["div-proc","divided-rectangle","divided-process"],handler:zJ},{semanticName:"Extract",name:"Triangle",shortName:"tri",description:"Extraction process",aliases:["extract","triangle"],handler:pte},{semanticName:"Internal Storage",name:"Window Pane",shortName:"win-pane",description:"Internal storage",aliases:["internal-storage","window-pane"],handler:bte},{semanticName:"Junction",name:"Filled Circle",shortName:"f-circ",description:"Junction point",aliases:["junction","filled-circle"],handler:HJ},{semanticName:"Loop Limit",name:"Trapezoidal Pentagon",shortName:"notch-pent",description:"Loop limit step",aliases:["loop-limit","notched-pentagon"],handler:fte},{semanticName:"Manual File",name:"Flipped Triangle",shortName:"flip-tri",description:"Manual file operation",aliases:["manual-file","flipped-triangle"],handler:WJ},{semanticName:"Manual Input",name:"Sloped Rectangle",shortName:"sl-rect",description:"Manual input step",aliases:["manual-input","sloped-rectangle"],handler:Vee},{semanticName:"Multi-Document",name:"Stacked Document",shortName:"docs",description:"Multiple documents",aliases:["documents","st-doc","stacked-document"],handler:_ee},{semanticName:"Multi-Process",name:"Stacked Rectangle",shortName:"st-rect",description:"Multiple processes",aliases:["procs","processes","stacked-rectangle"],handler:Cee},{semanticName:"Stored Data",name:"Bow Tie Rectangle",shortName:"bow-rect",description:"Stored data",aliases:["stored-data","bow-tie-rectangle"],handler:wJ},{semanticName:"Summary",name:"Crossed Circle",shortName:"cross-circ",description:"Summary",aliases:["summary","crossed-circle"],handler:_J},{semanticName:"Tagged Document",name:"Tagged Document",shortName:"tag-doc",description:"Tagged document",aliases:["tag-doc","tagged-document"],handler:ite},{semanticName:"Tagged Process",name:"Tagged Rectangle",shortName:"tag-rect",description:"Tagged process",aliases:["tagged-rectangle","tag-proc","tagged-process"],handler:rte},{semanticName:"Paper Tape",name:"Flag",shortName:"flag",description:"Paper tape",aliases:["paper-tape"],handler:vte},{semanticName:"Odd",name:"Odd",shortName:"odd",description:"Odd shape",internalAliases:["rect_left_inv_arrow"],handler:Iee},{semanticName:"Lined Document",name:"Lined Document",shortName:"lin-doc",description:"Lined document",aliases:["lined-document"],handler:Eee}],LRe=o(()=>{let e=[...Object.entries({state:Xee,choice:CJ,note:Lee,rectWithTitle:Pee,labelRect:pee,iconSquare:lee,iconCircle:iee,icon:ree,iconRounded:see,imageSquare:uee,anchor:xJ,kanbanItem:Dte,mindmapCircle:Bte,defaultMindmapNode:Ote,classBox:Ste,erBox:H9,requirementBox:Ate}),...DRe.flatMap(r=>[r.shortName,..."aliases"in r?r.aliases:[],..."internalAliases"in r?r.internalAliases:[]].map(i=>[i,r.handler]))];return Object.fromEntries(e)},"generateShapeMap"),q9=LRe();o($te,"isValidShape")});var RRe,cw,zte=M(()=>{"use strict";yr();k2();Xt();pt();W9();tr();gr();ci();RRe="flowchart-",cw=class{constructor(){this.vertexCounter=0;this.config=ge();this.vertices=new Map;this.edges=[];this.classes=new Map;this.subGraphs=[];this.subGraphLookup=new Map;this.tooltips=new Map;this.subCount=0;this.firstGraphFlag=!0;this.secCount=-1;this.posCrossRef=[];this.funs=[];this.setAccTitle=Rr;this.setAccDescription=Ir;this.setDiagramTitle=$r;this.getAccTitle=Mr;this.getAccDescription=Or;this.getDiagramTitle=Pr;this.funs.push(this.setupToolTips.bind(this)),this.addVertex=this.addVertex.bind(this),this.firstGraph=this.firstGraph.bind(this),this.setDirection=this.setDirection.bind(this),this.addSubGraph=this.addSubGraph.bind(this),this.addLink=this.addLink.bind(this),this.setLink=this.setLink.bind(this),this.updateLink=this.updateLink.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.destructLink=this.destructLink.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setTooltip=this.setTooltip.bind(this),this.updateLinkInterpolate=this.updateLinkInterpolate.bind(this),this.setClickFun=this.setClickFun.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.lex={firstGraph:this.firstGraph.bind(this)},this.clear(),this.setGen("gen-2")}static{o(this,"FlowDB")}sanitizeText(e){return tt.sanitizeText(e,this.config)}lookUpDomId(e){for(let r of this.vertices.values())if(r.id===e)return r.domId;return e}addVertex(e,r,n,i,a,s,l={},u){if(!e||e.trim().length===0)return;let h;if(u!==void 0){let m;u.includes(`
+`)?m=u+`
+`:m=`{
+`+u+`
+}`,h=Kh(m,{schema:jh})}let f=this.edges.find(m=>m.id===e);if(f){let m=h;m?.animate!==void 0&&(f.animate=m.animate),m?.animation!==void 0&&(f.animation=m.animation),m?.curve!==void 0&&(f.interpolate=m.curve);return}let d,p=this.vertices.get(e);if(p===void 0&&(p={id:e,labelType:"text",domId:RRe+e+"-"+this.vertexCounter,styles:[],classes:[]},this.vertices.set(e,p)),this.vertexCounter++,r!==void 0?(this.config=ge(),d=this.sanitizeText(r.text.trim()),p.labelType=r.type,d.startsWith('"')&&d.endsWith('"')&&(d=d.substring(1,d.length-1)),p.text=d):p.text===void 0&&(p.text=e),n!==void 0&&(p.type=n),i?.forEach(m=>{p.styles.push(m)}),a?.forEach(m=>{p.classes.push(m)}),s!==void 0&&(p.dir=s),p.props===void 0?p.props=l:l!==void 0&&Object.assign(p.props,l),h!==void 0){if(h.shape){if(h.shape!==h.shape.toLowerCase()||h.shape.includes("_"))throw new Error(`No such shape: ${h.shape}. Shape names should be lowercase.`);if(!$te(h.shape))throw new Error(`No such shape: ${h.shape}.`);p.type=h?.shape}h?.label&&(p.text=h?.label),h?.icon&&(p.icon=h?.icon,!h.label?.trim()&&p.text===e&&(p.text="")),h?.form&&(p.form=h?.form),h?.pos&&(p.pos=h?.pos),h?.img&&(p.img=h?.img,!h.label?.trim()&&p.text===e&&(p.text="")),h?.constraint&&(p.constraint=h.constraint),h.w&&(p.assetWidth=Number(h.w)),h.h&&(p.assetHeight=Number(h.h))}}addSingleLink(e,r,n,i){let l={start:e,end:r,type:void 0,text:"",labelType:"text",classes:[],isUserDefinedId:!1,interpolate:this.edges.defaultInterpolate};X.info("abc78 Got edge...",l);let u=n.text;if(u!==void 0&&(l.text=this.sanitizeText(u.text.trim()),l.text.startsWith('"')&&l.text.endsWith('"')&&(l.text=l.text.substring(1,l.text.length-1)),l.labelType=u.type),n!==void 0&&(l.type=n.type,l.stroke=n.stroke,l.length=n.length>10?10:n.length),i&&!this.edges.some(h=>h.id===i))l.id=i,l.isUserDefinedId=!0;else{let h=this.edges.filter(f=>f.start===l.start&&f.end===l.end);h.length===0?l.id=xc(l.start,l.end,{counter:0,prefix:"L"}):l.id=xc(l.start,l.end,{counter:h.length+1,prefix:"L"})}if(this.edges.length<(this.config.maxEdges??500))X.info("Pushing edge..."),this.edges.push(l);else throw new Error(`Edge limit exceeded. ${this.edges.length} edges found, but the limit is ${this.config.maxEdges}.
+
+Initialize mermaid with maxEdges set to a higher number to allow more edges.
+You cannot set this config via configuration inside the diagram as it is a secure config.
+You have to call mermaid.initialize.`)}isLinkData(e){return e!==null&&typeof e=="object"&&"id"in e&&typeof e.id=="string"}addLink(e,r,n){let i=this.isLinkData(n)?n.id.replace("@",""):void 0;X.info("addLink",e,r,i);for(let a of e)for(let s of r){let l=a===e[e.length-1],u=s===r[0];l&&u?this.addSingleLink(a,s,n,i):this.addSingleLink(a,s,n,void 0)}}updateLinkInterpolate(e,r){e.forEach(n=>{n==="default"?this.edges.defaultInterpolate=r:this.edges[n].interpolate=r})}updateLink(e,r){e.forEach(n=>{if(typeof n=="number"&&n>=this.edges.length)throw new Error(`The index ${n} for linkStyle is out of bounds. Valid indices for linkStyle are between 0 and ${this.edges.length-1}. (Help: Ensure that the index is within the range of existing edges.)`);n==="default"?this.edges.defaultStyle=r:(this.edges[n].style=r,(this.edges[n]?.style?.length??0)>0&&!this.edges[n]?.style?.some(i=>i?.startsWith("fill"))&&this.edges[n]?.style?.push("fill:none"))})}addClass(e,r){let n=r.join().replace(/\\,/g,"\xA7\xA7\xA7").replace(/,/g,";").replace(/§§§/g,",").split(";");e.split(",").forEach(i=>{let a=this.classes.get(i);a===void 0&&(a={id:i,styles:[],textStyles:[]},this.classes.set(i,a)),n?.forEach(s=>{if(/color/.exec(s)){let l=s.replace("fill","bgFill");a.textStyles.push(l)}a.styles.push(s)})})}setDirection(e){this.direction=e.trim(),/.*/.exec(this.direction)&&(this.direction="LR"),/.*v/.exec(this.direction)&&(this.direction="TB"),this.direction==="TD"&&(this.direction="TB")}setClass(e,r){for(let n of e.split(",")){let i=this.vertices.get(n);i&&i.classes.push(r);let a=this.edges.find(l=>l.id===n);a&&a.classes.push(r);let s=this.subGraphLookup.get(n);s&&s.classes.push(r)}}setTooltip(e,r){if(r!==void 0){r=this.sanitizeText(r);for(let n of e.split(","))this.tooltips.set(this.version==="gen-1"?this.lookUpDomId(n):n,r)}}setClickFun(e,r,n){let i=this.lookUpDomId(e);if(ge().securityLevel!=="loose"||r===void 0)return;let a=[];if(typeof n=="string"){a=n.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(let l=0;l
")),s.classed("hover",!0)}).on("mouseout",a=>{r.transition().duration(500).style("opacity",0),qe(a.currentTarget).classed("hover",!1)})}clear(e="gen-2"){this.vertices=new Map,this.classes=new Map,this.edges=[],this.funs=[this.setupToolTips.bind(this)],this.subGraphs=[],this.subGraphLookup=new Map,this.subCount=0,this.tooltips=new Map,this.firstGraphFlag=!0,this.version=e,this.config=ge(),Sr()}setGen(e){this.version=e||"gen-2"}defaultStyle(){return"fill:#ffa;stroke: #f66; stroke-width: 3px; stroke-dasharray: 5, 5;fill:#ffa;stroke: #666;"}addSubGraph(e,r,n){let i=e.text.trim(),a=n.text;e===n&&/\s/.exec(n.text)&&(i=void 0);let l=o(p=>{let m={boolean:{},number:{},string:{}},g=[],y;return{nodeList:p.filter(function(x){let b=typeof x;return x.stmt&&x.stmt==="dir"?(y=x.value,!1):x.trim()===""?!1:b in m?m[b].hasOwnProperty(x)?!1:m[b][x]=!0:g.includes(x)?!1:g.push(x)}),dir:y}},"uniq")(r.flat()),u=l.nodeList,h=l.dir,f=ge().flowchart??{};if(h=h??(f.inheritDir?this.getDirection()??ge().direction??void 0:void 0),this.version==="gen-1")for(let p=0;p0&&r(l)?e>1?Rre(l,e-1,r,n,i):Mm(i,l):n||(i[i.length]=l)}return i}var Ac,Im=M(()=>{"use strict";Lw();Lre();o(Rre,"baseFlatten");Ac=Rre});function nMe(t){var e=t==null?0:t.length;return e?Ac(t,1):[]}var Qr,Rw=M(()=>{"use strict";Im();o(nMe,"flatten");Qr=nMe});function iMe(t){return AT(CT(t,void 0,Qr),t+"")}var Nre,Mre=M(()=>{"use strict";Rw();RL();ML();o(iMe,"flatRest");Nre=iMe});function aMe(t,e,r){var n=-1,i=t.length;e<0&&(e=-e>i?0:i+e),r=r>i?i:r,r<0&&(r+=i),i=e>r?0:r-e>>>0,e>>>=0;for(var a=Array(i);++n{"use strict";o(aMe,"baseSlice");Nw=aMe});function pMe(t){return dMe.test(t)}var sMe,oMe,lMe,cMe,uMe,hMe,fMe,dMe,Ire,Ore=M(()=>{"use strict";sMe="\\ud800-\\udfff",oMe="\\u0300-\\u036f",lMe="\\ufe20-\\ufe2f",cMe="\\u20d0-\\u20ff",uMe=oMe+lMe+cMe,hMe="\\ufe0e\\ufe0f",fMe="\\u200d",dMe=RegExp("["+fMe+sMe+uMe+hMe+"]");o(pMe,"hasUnicode");Ire=pMe});function mMe(t,e,r,n){var i=-1,a=t==null?0:t.length;for(n&&a&&(r=t[++i]);++i{"use strict";o(mMe,"arrayReduce");Pre=mMe});function gMe(t,e){return t&&$o(e,qr(e),t)}var Fre,$re=M(()=>{"use strict";Hd();Sc();o(gMe,"baseAssign");Fre=gMe});function yMe(t,e){return t&&$o(e,Rs(e),t)}var zre,Gre=M(()=>{"use strict";Hd();qh();o(yMe,"baseAssignIn");zre=yMe});function vMe(t,e){for(var r=-1,n=t==null?0:t.length,i=0,a=[];++r