diff --git a/.gitattributes b/.gitattributes index 680e7f4b0c98fa6ef6f6c2d73b95cc462e5a7fec..12ab58c8f49c0ffb2fc1a91981e794dbe09f6fc7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -62,3 +62,14 @@ node_modules/bare-url/prebuilds/win32-x64/bare-url.bare filter=lfs diff=lfs merg node_modules/better-sqlite3/build/Release/better_sqlite3.node filter=lfs diff=lfs merge=lfs -text node_modules/concurrently/docs/demo.gif filter=lfs diff=lfs merge=lfs -text node_modules/exif-parser/test/starfish.jpg filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/hairstreak.jpg filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/lenna.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/nburling-public.gif filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Dekker.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Sorokin.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Wu.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Dekker.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Sorokin.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Wu.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin_FloydSteinberg.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/rnaples-offsets-public.gif filter=lfs diff=lfs merge=lfs -text diff --git a/node_modules/fontkit/src/layout/Script.js b/node_modules/fontkit/src/layout/Script.js new file mode 100644 index 0000000000000000000000000000000000000000..80106b6499f7a2d5a776ea1bf0590c74d09bcbe7 --- /dev/null +++ b/node_modules/fontkit/src/layout/Script.js @@ -0,0 +1,231 @@ +import {getScript} from 'unicode-properties'; + +// This maps the Unicode Script property to an OpenType script tag +// Data from http://www.microsoft.com/typography/otspec/scripttags.htm +// and http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt. +const UNICODE_SCRIPTS = { + Caucasian_Albanian: 'aghb', + Arabic: 'arab', + Imperial_Aramaic: 'armi', + Armenian: 'armn', + Avestan: 'avst', + Balinese: 'bali', + Bamum: 'bamu', + Bassa_Vah: 'bass', + Batak: 'batk', + Bengali: ['bng2', 'beng'], + Bopomofo: 'bopo', + Brahmi: 'brah', + Braille: 'brai', + Buginese: 'bugi', + Buhid: 'buhd', + Chakma: 'cakm', + Canadian_Aboriginal: 'cans', + Carian: 'cari', + Cham: 'cham', + Cherokee: 'cher', + Coptic: 'copt', + Cypriot: 'cprt', + Cyrillic: 'cyrl', + Devanagari: ['dev2', 'deva'], + Deseret: 'dsrt', + Duployan: 'dupl', + Egyptian_Hieroglyphs: 'egyp', + Elbasan: 'elba', + Ethiopic: 'ethi', + Georgian: 'geor', + Glagolitic: 'glag', + Gothic: 'goth', + Grantha: 'gran', + Greek: 'grek', + Gujarati: ['gjr2', 'gujr'], + Gurmukhi: ['gur2', 'guru'], + Hangul: 'hang', + Han: 'hani', + Hanunoo: 'hano', + Hebrew: 'hebr', + Hiragana: 'hira', + Pahawh_Hmong: 'hmng', + Katakana_Or_Hiragana: 'hrkt', + Old_Italic: 'ital', + Javanese: 'java', + Kayah_Li: 'kali', + Katakana: 'kana', + Kharoshthi: 'khar', + Khmer: 'khmr', + Khojki: 'khoj', + Kannada: ['knd2', 'knda'], + Kaithi: 'kthi', + Tai_Tham: 'lana', + Lao: 'lao ', + Latin: 'latn', + Lepcha: 'lepc', + Limbu: 'limb', + Linear_A: 'lina', + Linear_B: 'linb', + Lisu: 'lisu', + Lycian: 'lyci', + Lydian: 'lydi', + Mahajani: 'mahj', + Mandaic: 'mand', + Manichaean: 'mani', + Mende_Kikakui: 'mend', + Meroitic_Cursive: 'merc', + Meroitic_Hieroglyphs: 'mero', + Malayalam: ['mlm2', 'mlym'], + Modi: 'modi', + Mongolian: 'mong', + Mro: 'mroo', + Meetei_Mayek: 'mtei', + Myanmar: ['mym2', 'mymr'], + Old_North_Arabian: 'narb', + Nabataean: 'nbat', + Nko: 'nko ', + Ogham: 'ogam', + Ol_Chiki: 'olck', + Old_Turkic: 'orkh', + Oriya: ['ory2', 'orya'], + Osmanya: 'osma', + Palmyrene: 'palm', + Pau_Cin_Hau: 'pauc', + Old_Permic: 'perm', + Phags_Pa: 'phag', + Inscriptional_Pahlavi: 'phli', + Psalter_Pahlavi: 'phlp', + Phoenician: 'phnx', + Miao: 'plrd', + Inscriptional_Parthian: 'prti', + Rejang: 'rjng', + Runic: 'runr', + Samaritan: 'samr', + Old_South_Arabian: 'sarb', + Saurashtra: 'saur', + Shavian: 'shaw', + Sharada: 'shrd', + Siddham: 'sidd', + Khudawadi: 'sind', + Sinhala: 'sinh', + Sora_Sompeng: 'sora', + Sundanese: 'sund', + Syloti_Nagri: 'sylo', + Syriac: 'syrc', + Tagbanwa: 'tagb', + Takri: 'takr', + Tai_Le: 'tale', + New_Tai_Lue: 'talu', + Tamil: ['tml2', 'taml'], + Tai_Viet: 'tavt', + Telugu: ['tel2', 'telu'], + Tifinagh: 'tfng', + Tagalog: 'tglg', + Thaana: 'thaa', + Thai: 'thai', + Tibetan: 'tibt', + Tirhuta: 'tirh', + Ugaritic: 'ugar', + Vai: 'vai ', + Warang_Citi: 'wara', + Old_Persian: 'xpeo', + Cuneiform: 'xsux', + Yi: 'yi ', + Inherited: 'zinh', + Common: 'zyyy', + Unknown: 'zzzz' +}; + +const OPENTYPE_SCRIPTS = {}; +for (let script in UNICODE_SCRIPTS) { + let tag = UNICODE_SCRIPTS[script]; + if (Array.isArray(tag)) { + for (let t of tag) { + OPENTYPE_SCRIPTS[t] = script; + } + } else { + OPENTYPE_SCRIPTS[tag] = script; + } +} + +export function fromUnicode(script) { + return UNICODE_SCRIPTS[script]; +} + +export function fromOpenType(tag) { + return OPENTYPE_SCRIPTS[tag]; +} + +export function forString(string) { + let len = string.length; + let idx = 0; + while (idx < len) { + let code = string.charCodeAt(idx++); + + // Check if this is a high surrogate + if (0xd800 <= code && code <= 0xdbff && idx < len) { + let next = string.charCodeAt(idx); + + // Check if this is a low surrogate + if (0xdc00 <= next && next <= 0xdfff) { + idx++; + code = ((code & 0x3FF) << 10) + (next & 0x3FF) + 0x10000; + } + } + + let script = getScript(code); + if (script !== 'Common' && script !== 'Inherited' && script !== 'Unknown') { + return UNICODE_SCRIPTS[script]; + } + } + + return UNICODE_SCRIPTS.Unknown; +} + +export function forCodePoints(codePoints) { + for (let i = 0; i < codePoints.length; i++) { + let codePoint = codePoints[i]; + let script = getScript(codePoint); + if (script !== 'Common' && script !== 'Inherited' && script !== 'Unknown') { + return UNICODE_SCRIPTS[script]; + } + } + + return UNICODE_SCRIPTS.Unknown; +} + +// The scripts in this map are written from right to left +const RTL = { + arab: true, // Arabic + hebr: true, // Hebrew + syrc: true, // Syriac + thaa: true, // Thaana + cprt: true, // Cypriot Syllabary + khar: true, // Kharosthi + phnx: true, // Phoenician + 'nko ': true, // N'Ko + lydi: true, // Lydian + avst: true, // Avestan + armi: true, // Imperial Aramaic + phli: true, // Inscriptional Pahlavi + prti: true, // Inscriptional Parthian + sarb: true, // Old South Arabian + orkh: true, // Old Turkic, Orkhon Runic + samr: true, // Samaritan + mand: true, // Mandaic, Mandaean + merc: true, // Meroitic Cursive + mero: true, // Meroitic Hieroglyphs + + // Unicode 7.0 (not listed on http://www.microsoft.com/typography/otspec/scripttags.htm) + mani: true, // Manichaean + mend: true, // Mende Kikakui + nbat: true, // Nabataean + narb: true, // Old North Arabian + palm: true, // Palmyrene + phlp: true // Psalter Pahlavi +}; + +export function direction(script) { + if (RTL[script]) { + return 'rtl'; + } + + return 'ltr'; +} diff --git a/node_modules/fontkit/src/layout/UnicodeLayoutEngine.js b/node_modules/fontkit/src/layout/UnicodeLayoutEngine.js new file mode 100644 index 0000000000000000000000000000000000000000..68d5b9a08cb81691335ed0baf32e7755febaf2cb --- /dev/null +++ b/node_modules/fontkit/src/layout/UnicodeLayoutEngine.js @@ -0,0 +1,250 @@ +import {getCombiningClass} from 'unicode-properties'; + +/** + * This class is used when GPOS does not define 'mark' or 'mkmk' features + * for positioning marks relative to base glyphs. It uses the unicode + * combining class property to position marks. + * + * Based on code from Harfbuzz, thanks! + * https://github.com/behdad/harfbuzz/blob/master/src/hb-ot-shape-fallback.cc + */ +export default class UnicodeLayoutEngine { + constructor(font) { + this.font = font; + } + + positionGlyphs(glyphs, positions) { + // find each base + mark cluster, and position the marks relative to the base + let clusterStart = 0; + let clusterEnd = 0; + for (let index = 0; index < glyphs.length; index++) { + let glyph = glyphs[index]; + if (glyph.isMark) { // TODO: handle ligatures + clusterEnd = index; + } else { + if (clusterStart !== clusterEnd) { + this.positionCluster(glyphs, positions, clusterStart, clusterEnd); + } + + clusterStart = clusterEnd = index; + } + } + + if (clusterStart !== clusterEnd) { + this.positionCluster(glyphs, positions, clusterStart, clusterEnd); + } + + return positions; + } + + positionCluster(glyphs, positions, clusterStart, clusterEnd) { + let base = glyphs[clusterStart]; + let baseBox = base.cbox.copy(); + + // adjust bounding box for ligature glyphs + if (base.codePoints.length > 1) { + // LTR. TODO: RTL support. + baseBox.minX += ((base.codePoints.length - 1) * baseBox.width) / base.codePoints.length; + } + + let xOffset = -positions[clusterStart].xAdvance; + let yOffset = 0; + let yGap = this.font.unitsPerEm / 16; + + // position each of the mark glyphs relative to the base glyph + for (let index = clusterStart + 1; index <= clusterEnd; index++) { + let mark = glyphs[index]; + let markBox = mark.cbox; + let position = positions[index]; + + let combiningClass = this.getCombiningClass(mark.codePoints[0]); + + if (combiningClass !== 'Not_Reordered') { + position.xOffset = position.yOffset = 0; + + // x positioning + switch (combiningClass) { + case 'Double_Above': + case 'Double_Below': + // LTR. TODO: RTL support. + position.xOffset += baseBox.minX - markBox.width / 2 - markBox.minX; + break; + + case 'Attached_Below_Left': + case 'Below_Left': + case 'Above_Left': + // left align + position.xOffset += baseBox.minX - markBox.minX; + break; + + case 'Attached_Above_Right': + case 'Below_Right': + case 'Above_Right': + // right align + position.xOffset += baseBox.maxX - markBox.width - markBox.minX; + break; + + default: // Attached_Below, Attached_Above, Below, Above, other + // center align + position.xOffset += baseBox.minX + (baseBox.width - markBox.width) / 2 - markBox.minX; + } + + // y positioning + switch (combiningClass) { + case 'Double_Below': + case 'Below_Left': + case 'Below': + case 'Below_Right': + case 'Attached_Below_Left': + case 'Attached_Below': + // add a small gap between the glyphs if they are not attached + if (combiningClass === 'Attached_Below_Left' || combiningClass === 'Attached_Below') { + baseBox.minY += yGap; + } + + position.yOffset = -baseBox.minY - markBox.maxY; + baseBox.minY += markBox.height; + break; + + case 'Double_Above': + case 'Above_Left': + case 'Above': + case 'Above_Right': + case 'Attached_Above': + case 'Attached_Above_Right': + // add a small gap between the glyphs if they are not attached + if (combiningClass === 'Attached_Above' || combiningClass === 'Attached_Above_Right') { + baseBox.maxY += yGap; + } + + position.yOffset = baseBox.maxY - markBox.minY; + baseBox.maxY += markBox.height; + break; + } + + position.xAdvance = position.yAdvance = 0; + position.xOffset += xOffset; + position.yOffset += yOffset; + + } else { + xOffset -= position.xAdvance; + yOffset -= position.yAdvance; + } + } + + return; + } + + getCombiningClass(codePoint) { + let combiningClass = getCombiningClass(codePoint); + + // Thai / Lao need some per-character work + if ((codePoint & ~0xff) === 0x0e00) { + if (combiningClass === 'Not_Reordered') { + switch (codePoint) { + case 0x0e31: + case 0x0e34: + case 0x0e35: + case 0x0e36: + case 0x0e37: + case 0x0e47: + case 0x0e4c: + case 0x0e3d: + case 0x0e4e: + return 'Above_Right'; + + case 0x0eb1: + case 0x0eb4: + case 0x0eb5: + case 0x0eb6: + case 0x0eb7: + case 0x0ebb: + case 0x0ecc: + case 0x0ecd: + return 'Above'; + + case 0x0ebc: + return 'Below'; + } + } else if (codePoint === 0x0e3a) { // virama + return 'Below_Right'; + } + } + + switch (combiningClass) { + // Hebrew + + case 'CCC10': // sheva + case 'CCC11': // hataf segol + case 'CCC12': // hataf patah + case 'CCC13': // hataf qamats + case 'CCC14': // hiriq + case 'CCC15': // tsere + case 'CCC16': // segol + case 'CCC17': // patah + case 'CCC18': // qamats + case 'CCC20': // qubuts + case 'CCC22': // meteg + return 'Below'; + + case 'CCC23': // rafe + return 'Attached_Above'; + + case 'CCC24': // shin dot + return 'Above_Right'; + + case 'CCC25': // sin dot + case 'CCC19': // holam + return 'Above_Left'; + + case 'CCC26': // point varika + return 'Above'; + + case 'CCC21': // dagesh + break; + + // Arabic and Syriac + + case 'CCC27': // fathatan + case 'CCC28': // dammatan + case 'CCC30': // fatha + case 'CCC31': // damma + case 'CCC33': // shadda + case 'CCC34': // sukun + case 'CCC35': // superscript alef + case 'CCC36': // superscript alaph + return 'Above'; + + case 'CCC29': // kasratan + case 'CCC32': // kasra + return 'Below'; + + // Thai + + case 'CCC103': // sara u / sara uu + return 'Below_Right'; + + case 'CCC107': // mai + return 'Above_Right'; + + // Lao + + case 'CCC118': // sign u / sign uu + return 'Below'; + + case 'CCC122': // mai + return 'Above'; + + // Tibetan + + case 'CCC129': // sign aa + case 'CCC132': // sign u + return 'Below'; + + case 'CCC130': // sign i + return 'Above'; + } + + return combiningClass; + } +} diff --git a/node_modules/fontkit/src/node.js b/node_modules/fontkit/src/node.js new file mode 100644 index 0000000000000000000000000000000000000000..f496ea026ec6562621de35b55038b0765fe53fca --- /dev/null +++ b/node_modules/fontkit/src/node.js @@ -0,0 +1,17 @@ +import { registerFormat, create, defaultLanguage, setDefaultLanguage } from './base'; +import { open, openSync } from './fs'; +import TTFFont from './TTFFont'; +import WOFFFont from './WOFFFont'; +import WOFF2Font from './WOFF2Font'; +import TrueTypeCollection from './TrueTypeCollection'; +import DFont from './DFont'; + +// Register font formats +registerFormat(TTFFont); +registerFormat(WOFFFont); +registerFormat(WOFF2Font); +registerFormat(TrueTypeCollection); +registerFormat(DFont); + +export * from './base'; +export * from './fs'; diff --git a/node_modules/fontkit/src/opentype/GPOSProcessor.js b/node_modules/fontkit/src/opentype/GPOSProcessor.js new file mode 100644 index 0000000000000000000000000000000000000000..6a2c1f9fc9a027f17e51fb1690dea7a809cd5893 --- /dev/null +++ b/node_modules/fontkit/src/opentype/GPOSProcessor.js @@ -0,0 +1,353 @@ +import OTProcessor from './OTProcessor'; + +export default class GPOSProcessor extends OTProcessor { + applyPositionValue(sequenceIndex, value) { + let position = this.positions[this.glyphIterator.peekIndex(sequenceIndex)]; + if (value.xAdvance != null) { + position.xAdvance += value.xAdvance; + } + + if (value.yAdvance != null) { + position.yAdvance += value.yAdvance; + } + + if (value.xPlacement != null) { + position.xOffset += value.xPlacement; + } + + if (value.yPlacement != null) { + position.yOffset += value.yPlacement; + } + + // Adjustments for font variations + let variationProcessor = this.font._variationProcessor; + let variationStore = this.font.GDEF && this.font.GDEF.itemVariationStore; + if (variationProcessor && variationStore) { + if (value.xPlaDevice) { + position.xOffset += variationProcessor.getDelta(variationStore, value.xPlaDevice.a, value.xPlaDevice.b); + } + + if (value.yPlaDevice) { + position.yOffset += variationProcessor.getDelta(variationStore, value.yPlaDevice.a, value.yPlaDevice.b); + } + + if (value.xAdvDevice) { + position.xAdvance += variationProcessor.getDelta(variationStore, value.xAdvDevice.a, value.xAdvDevice.b); + } + + if (value.yAdvDevice) { + position.yAdvance += variationProcessor.getDelta(variationStore, value.yAdvDevice.a, value.yAdvDevice.b); + } + } + + // TODO: device tables + } + + applyLookup(lookupType, table) { + switch (lookupType) { + case 1: { // Single positioning value + let index = this.coverageIndex(table.coverage); + if (index === -1) { + return false; + } + + switch (table.version) { + case 1: + this.applyPositionValue(0, table.value); + break; + + case 2: + this.applyPositionValue(0, table.values.get(index)); + break; + } + + return true; + } + + case 2: { // Pair Adjustment Positioning + let nextGlyph = this.glyphIterator.peek(); + if (!nextGlyph) { + return false; + } + + let index = this.coverageIndex(table.coverage); + if (index === -1) { + return false; + } + + switch (table.version) { + case 1: // Adjustments for glyph pairs + let set = table.pairSets.get(index); + + for (let pair of set) { + if (pair.secondGlyph === nextGlyph.id) { + this.applyPositionValue(0, pair.value1); + this.applyPositionValue(1, pair.value2); + return true; + } + } + + return false; + + case 2: // Class pair adjustment + let class1 = this.getClassID(this.glyphIterator.cur.id, table.classDef1); + let class2 = this.getClassID(nextGlyph.id, table.classDef2); + if (class1 === -1 || class2 === -1) { + return false; + } + + var pair = table.classRecords.get(class1).get(class2); + this.applyPositionValue(0, pair.value1); + this.applyPositionValue(1, pair.value2); + return true; + } + } + + case 3: { // Cursive Attachment Positioning + let nextIndex = this.glyphIterator.peekIndex(); + let nextGlyph = this.glyphs[nextIndex]; + if (!nextGlyph) { + return false; + } + + let curRecord = table.entryExitRecords[this.coverageIndex(table.coverage)]; + if (!curRecord || !curRecord.exitAnchor) { + return false; + } + + let nextRecord = table.entryExitRecords[this.coverageIndex(table.coverage, nextGlyph.id)]; + if (!nextRecord || !nextRecord.entryAnchor) { + return false; + } + + let entry = this.getAnchor(nextRecord.entryAnchor); + let exit = this.getAnchor(curRecord.exitAnchor); + + let cur = this.positions[this.glyphIterator.index]; + let next = this.positions[nextIndex]; + let d; + + switch (this.direction) { + case 'ltr': + cur.xAdvance = exit.x + cur.xOffset; + + d = entry.x + next.xOffset; + next.xAdvance -= d; + next.xOffset -= d; + break; + + case 'rtl': + d = exit.x + cur.xOffset; + cur.xAdvance -= d; + cur.xOffset -= d; + next.xAdvance = entry.x + next.xOffset; + break; + } + + if (this.glyphIterator.flags.rightToLeft) { + this.glyphIterator.cur.cursiveAttachment = nextIndex; + cur.yOffset = entry.y - exit.y; + } else { + nextGlyph.cursiveAttachment = this.glyphIterator.index; + cur.yOffset = exit.y - entry.y; + } + + return true; + } + + case 4: { // Mark to base positioning + let markIndex = this.coverageIndex(table.markCoverage); + if (markIndex === -1) { + return false; + } + + // search backward for a base glyph + let baseGlyphIndex = this.glyphIterator.index; + while (--baseGlyphIndex >= 0 && (this.glyphs[baseGlyphIndex].isMark || this.glyphs[baseGlyphIndex].ligatureComponent > 0)); + + if (baseGlyphIndex < 0) { + return false; + } + + let baseIndex = this.coverageIndex(table.baseCoverage, this.glyphs[baseGlyphIndex].id); + if (baseIndex === -1) { + return false; + } + + let markRecord = table.markArray[markIndex]; + let baseAnchor = table.baseArray[baseIndex][markRecord.class]; + this.applyAnchor(markRecord, baseAnchor, baseGlyphIndex); + return true; + } + + case 5: { // Mark to ligature positioning + let markIndex = this.coverageIndex(table.markCoverage); + if (markIndex === -1) { + return false; + } + + // search backward for a base glyph + let baseGlyphIndex = this.glyphIterator.index; + while (--baseGlyphIndex >= 0 && this.glyphs[baseGlyphIndex].isMark); + + if (baseGlyphIndex < 0) { + return false; + } + + let ligIndex = this.coverageIndex(table.ligatureCoverage, this.glyphs[baseGlyphIndex].id); + if (ligIndex === -1) { + return false; + } + + let ligAttach = table.ligatureArray[ligIndex]; + let markGlyph = this.glyphIterator.cur; + let ligGlyph = this.glyphs[baseGlyphIndex]; + let compIndex = ligGlyph.ligatureID && ligGlyph.ligatureID === markGlyph.ligatureID && (markGlyph.ligatureComponent > 0) + ? Math.min(markGlyph.ligatureComponent, ligGlyph.codePoints.length) - 1 + : ligGlyph.codePoints.length - 1; + + let markRecord = table.markArray[markIndex]; + let baseAnchor = ligAttach[compIndex][markRecord.class]; + this.applyAnchor(markRecord, baseAnchor, baseGlyphIndex); + return true; + } + + case 6: { // Mark to mark positioning + let mark1Index = this.coverageIndex(table.mark1Coverage); + if (mark1Index === -1) { + return false; + } + + // get the previous mark to attach to + let prevIndex = this.glyphIterator.peekIndex(-1); + let prev = this.glyphs[prevIndex]; + if (!prev || !prev.isMark) { + return false; + } + + let cur = this.glyphIterator.cur; + + // The following logic was borrowed from Harfbuzz + let good = false; + if (cur.ligatureID === prev.ligatureID) { + if (!cur.ligatureID) { // Marks belonging to the same base + good = true; + } else if (cur.ligatureComponent === prev.ligatureComponent) { // Marks belonging to the same ligature component + good = true; + } + } else { + // If ligature ids don't match, it may be the case that one of the marks + // itself is a ligature, in which case match. + if ((cur.ligatureID && !cur.ligatureComponent) || (prev.ligatureID && !prev.ligatureComponent)) { + good = true; + } + } + + if (!good) { + return false; + } + + let mark2Index = this.coverageIndex(table.mark2Coverage, prev.id); + if (mark2Index === -1) { + return false; + } + + let markRecord = table.mark1Array[mark1Index]; + let baseAnchor = table.mark2Array[mark2Index][markRecord.class]; + this.applyAnchor(markRecord, baseAnchor, prevIndex); + return true; + } + + case 7: // Contextual positioning + return this.applyContext(table); + + case 8: // Chaining contextual positioning + return this.applyChainingContext(table); + + case 9: // Extension positioning + return this.applyLookup(table.lookupType, table.extension); + + default: + throw new Error(`Unsupported GPOS table: ${lookupType}`); + } + } + + applyAnchor(markRecord, baseAnchor, baseGlyphIndex) { + let baseCoords = this.getAnchor(baseAnchor); + let markCoords = this.getAnchor(markRecord.markAnchor); + + let basePos = this.positions[baseGlyphIndex]; + let markPos = this.positions[this.glyphIterator.index]; + + markPos.xOffset = baseCoords.x - markCoords.x; + markPos.yOffset = baseCoords.y - markCoords.y; + this.glyphIterator.cur.markAttachment = baseGlyphIndex; + } + + getAnchor(anchor) { + // TODO: contour point, device tables + let x = anchor.xCoordinate; + let y = anchor.yCoordinate; + + // Adjustments for font variations + let variationProcessor = this.font._variationProcessor; + let variationStore = this.font.GDEF && this.font.GDEF.itemVariationStore; + if (variationProcessor && variationStore) { + if (anchor.xDeviceTable) { + x += variationProcessor.getDelta(variationStore, anchor.xDeviceTable.a, anchor.xDeviceTable.b); + } + + if (anchor.yDeviceTable) { + y += variationProcessor.getDelta(variationStore, anchor.yDeviceTable.a, anchor.yDeviceTable.b); + } + } + + return { x, y }; + } + + applyFeatures(userFeatures, glyphs, advances) { + super.applyFeatures(userFeatures, glyphs, advances); + + for (var i = 0; i < this.glyphs.length; i++) { + this.fixCursiveAttachment(i); + } + + this.fixMarkAttachment(); + } + + fixCursiveAttachment(i) { + let glyph = this.glyphs[i]; + if (glyph.cursiveAttachment != null) { + let j = glyph.cursiveAttachment; + + glyph.cursiveAttachment = null; + this.fixCursiveAttachment(j); + + this.positions[i].yOffset += this.positions[j].yOffset; + } + } + + fixMarkAttachment() { + for (let i = 0; i < this.glyphs.length; i++) { + let glyph = this.glyphs[i]; + if (glyph.markAttachment != null) { + let j = glyph.markAttachment; + + this.positions[i].xOffset += this.positions[j].xOffset; + this.positions[i].yOffset += this.positions[j].yOffset; + + if (this.direction === 'ltr') { + for (let k = j; k < i; k++) { + this.positions[i].xOffset -= this.positions[k].xAdvance; + this.positions[i].yOffset -= this.positions[k].yAdvance; + } + } else { + for (let k = j + 1; k < i + 1; k++) { + this.positions[i].xOffset += this.positions[k].xAdvance; + this.positions[i].yOffset += this.positions[k].yAdvance; + } + } + } + } + } +} diff --git a/node_modules/fontkit/src/opentype/GSUBProcessor.js b/node_modules/fontkit/src/opentype/GSUBProcessor.js new file mode 100644 index 0000000000000000000000000000000000000000..f5672d5db6fe3061fca32aae58cf7dde5ed2aac1 --- /dev/null +++ b/node_modules/fontkit/src/opentype/GSUBProcessor.js @@ -0,0 +1,192 @@ +import OTProcessor from './OTProcessor'; +import GlyphInfo from './GlyphInfo'; + +export default class GSUBProcessor extends OTProcessor { + applyLookup(lookupType, table) { + switch (lookupType) { + case 1: { // Single Substitution + let index = this.coverageIndex(table.coverage); + if (index === -1) { + return false; + } + + let glyph = this.glyphIterator.cur; + switch (table.version) { + case 1: + glyph.id = (glyph.id + table.deltaGlyphID) & 0xffff; + break; + + case 2: + glyph.id = table.substitute.get(index); + break; + } + + return true; + } + + case 2: { // Multiple Substitution + let index = this.coverageIndex(table.coverage); + if (index !== -1) { + let sequence = table.sequences.get(index); + + if (sequence.length === 0) { + // If the sequence length is zero, delete the glyph. + // The OpenType spec disallows this, but seems like Harfbuzz and Uniscribe allow it. + this.glyphs.splice(this.glyphIterator.index, 1); + return true; + } + + this.glyphIterator.cur.id = sequence[0]; + this.glyphIterator.cur.ligatureComponent = 0; + + let features = this.glyphIterator.cur.features; + let curGlyph = this.glyphIterator.cur; + let replacement = sequence.slice(1).map((gid, i) => { + let glyph = new GlyphInfo(this.font, gid, undefined, features); + glyph.shaperInfo = curGlyph.shaperInfo; + glyph.isLigated = curGlyph.isLigated; + glyph.ligatureComponent = i + 1; + glyph.substituted = true; + glyph.isMultiplied = true; + return glyph; + }); + + this.glyphs.splice(this.glyphIterator.index + 1, 0, ...replacement); + return true; + } + + return false; + } + + case 3: { // Alternate Substitution + let index = this.coverageIndex(table.coverage); + if (index !== -1) { + let USER_INDEX = 0; // TODO + this.glyphIterator.cur.id = table.alternateSet.get(index)[USER_INDEX]; + return true; + } + + return false; + } + + case 4: { // Ligature Substitution + let index = this.coverageIndex(table.coverage); + if (index === -1) { + return false; + } + + for (let ligature of table.ligatureSets.get(index)) { + let matched = this.sequenceMatchIndices(1, ligature.components); + if (!matched) { + continue; + } + + let curGlyph = this.glyphIterator.cur; + + // Concatenate all of the characters the new ligature will represent + let characters = curGlyph.codePoints.slice(); + for (let index of matched) { + characters.push(...this.glyphs[index].codePoints); + } + + // Create the replacement ligature glyph + let ligatureGlyph = new GlyphInfo(this.font, ligature.glyph, characters, curGlyph.features); + ligatureGlyph.shaperInfo = curGlyph.shaperInfo; + ligatureGlyph.isLigated = true; + ligatureGlyph.substituted = true; + + // From Harfbuzz: + // - If it *is* a mark ligature, we don't allocate a new ligature id, and leave + // the ligature to keep its old ligature id. This will allow it to attach to + // a base ligature in GPOS. Eg. if the sequence is: LAM,LAM,SHADDA,FATHA,HEH, + // and LAM,LAM,HEH for a ligature, they will leave SHADDA and FATHA with a + // ligature id and component value of 2. Then if SHADDA,FATHA form a ligature + // later, we don't want them to lose their ligature id/component, otherwise + // GPOS will fail to correctly position the mark ligature on top of the + // LAM,LAM,HEH ligature. See https://bugzilla.gnome.org/show_bug.cgi?id=676343 + // + // - If a ligature is formed of components that some of which are also ligatures + // themselves, and those ligature components had marks attached to *their* + // components, we have to attach the marks to the new ligature component + // positions! Now *that*'s tricky! And these marks may be following the + // last component of the whole sequence, so we should loop forward looking + // for them and update them. + // + // Eg. the sequence is LAM,LAM,SHADDA,FATHA,HEH, and the font first forms a + // 'calt' ligature of LAM,HEH, leaving the SHADDA and FATHA with a ligature + // id and component == 1. Now, during 'liga', the LAM and the LAM-HEH ligature + // form a LAM-LAM-HEH ligature. We need to reassign the SHADDA and FATHA to + // the new ligature with a component value of 2. + // + // This in fact happened to a font... See https://bugzilla.gnome.org/show_bug.cgi?id=437633 + let isMarkLigature = curGlyph.isMark; + for (let i = 0; i < matched.length && isMarkLigature; i++) { + isMarkLigature = this.glyphs[matched[i]].isMark; + } + + ligatureGlyph.ligatureID = isMarkLigature ? null : this.ligatureID++; + + let lastLigID = curGlyph.ligatureID; + let lastNumComps = curGlyph.codePoints.length; + let curComps = lastNumComps; + let idx = this.glyphIterator.index + 1; + + // Set ligatureID and ligatureComponent on glyphs that were skipped in the matched sequence. + // This allows GPOS to attach marks to the correct ligature components. + for (let matchIndex of matched) { + // Don't assign new ligature components for mark ligatures (see above) + if (isMarkLigature) { + idx = matchIndex; + } else { + while (idx < matchIndex) { + var ligatureComponent = curComps - lastNumComps + Math.min(this.glyphs[idx].ligatureComponent || 1, lastNumComps); + this.glyphs[idx].ligatureID = ligatureGlyph.ligatureID; + this.glyphs[idx].ligatureComponent = ligatureComponent; + idx++; + } + } + + lastLigID = this.glyphs[idx].ligatureID; + lastNumComps = this.glyphs[idx].codePoints.length; + curComps += lastNumComps; + idx++; // skip base glyph + } + + // Adjust ligature components for any marks following + if (lastLigID && !isMarkLigature) { + for (let i = idx; i < this.glyphs.length; i++) { + if (this.glyphs[i].ligatureID === lastLigID) { + var ligatureComponent = curComps - lastNumComps + Math.min(this.glyphs[i].ligatureComponent || 1, lastNumComps); + this.glyphs[i].ligatureComponent = ligatureComponent; + } else { + break; + } + } + } + + // Delete the matched glyphs, and replace the current glyph with the ligature glyph + for (let i = matched.length - 1; i >= 0; i--) { + this.glyphs.splice(matched[i], 1); + } + + this.glyphs[this.glyphIterator.index] = ligatureGlyph; + return true; + } + + return false; + } + + case 5: // Contextual Substitution + return this.applyContext(table); + + case 6: // Chaining Contextual Substitution + return this.applyChainingContext(table); + + case 7: // Extension Substitution + return this.applyLookup(table.lookupType, table.extension); + + default: + throw new Error(`GSUB lookupType ${lookupType} is not supported`); + } + } +} diff --git a/node_modules/fontkit/src/opentype/GlyphInfo.js b/node_modules/fontkit/src/opentype/GlyphInfo.js new file mode 100644 index 0000000000000000000000000000000000000000..644a3a8e5b947ad3e1590e471a1301c7346377eb --- /dev/null +++ b/node_modules/fontkit/src/opentype/GlyphInfo.js @@ -0,0 +1,57 @@ +import {isMark} from 'unicode-properties'; +import OTProcessor from './OTProcessor'; + +export default class GlyphInfo { + constructor(font, id, codePoints = [], features) { + this._font = font; + this.codePoints = codePoints; + this.id = id; + + this.features = {}; + if (Array.isArray(features)) { + for (let i = 0; i < features.length; i++) { + let feature = features[i]; + this.features[feature] = true; + } + } else if (typeof features === 'object') { + Object.assign(this.features, features); + } + + this.ligatureID = null; + this.ligatureComponent = null; + this.isLigated = false; + this.cursiveAttachment = null; + this.markAttachment = null; + this.shaperInfo = null; + this.substituted = false; + this.isMultiplied = false; + } + + get id() { + return this._id; + } + + set id(id) { + this._id = id; + this.substituted = true; + + let GDEF = this._font.GDEF; + if (GDEF && GDEF.glyphClassDef) { + // TODO: clean this up + let classID = OTProcessor.prototype.getClassID(id, GDEF.glyphClassDef); + this.isBase = classID === 1; + this.isLigature = classID === 2; + this.isMark = classID === 3; + this.markAttachmentType = GDEF.markAttachClassDef ? OTProcessor.prototype.getClassID(id, GDEF.markAttachClassDef) : 0; + } else { + this.isMark = this.codePoints.length > 0 && this.codePoints.every(isMark); + this.isBase = !this.isMark; + this.isLigature = this.codePoints.length > 1; + this.markAttachmentType = 0; + } + } + + copy() { + return new GlyphInfo(this._font, this.id, this.codePoints, this.features); + } +} diff --git a/node_modules/fontkit/src/opentype/GlyphIterator.js b/node_modules/fontkit/src/opentype/GlyphIterator.js new file mode 100644 index 0000000000000000000000000000000000000000..b22ad30b44f5c2f32506e4770228666ab78ed0d6 --- /dev/null +++ b/node_modules/fontkit/src/opentype/GlyphIterator.js @@ -0,0 +1,70 @@ +export default class GlyphIterator { + constructor(glyphs, options) { + this.glyphs = glyphs; + this.reset(options); + } + + reset(options = {}, index = 0) { + this.options = options; + this.flags = options.flags || {}; + this.markAttachmentType = options.markAttachmentType || 0; + this.index = index; + } + + get cur() { + return this.glyphs[this.index] || null; + } + + shouldIgnore(glyph) { + return (this.flags.ignoreMarks && glyph.isMark) || + (this.flags.ignoreBaseGlyphs && glyph.isBase) || + (this.flags.ignoreLigatures && glyph.isLigature) || + (this.markAttachmentType && glyph.isMark && glyph.markAttachmentType !== this.markAttachmentType); + } + + move(dir) { + this.index += dir; + while (0 <= this.index && this.index < this.glyphs.length && this.shouldIgnore(this.glyphs[this.index])) { + this.index += dir; + } + + if (0 > this.index || this.index >= this.glyphs.length) { + return null; + } + + return this.glyphs[this.index]; + } + + next() { + return this.move(+1); + } + + prev() { + return this.move(-1); + } + + peek(count = 1) { + let idx = this.index; + let res = this.increment(count); + this.index = idx; + return res; + } + + peekIndex(count = 1) { + let idx = this.index; + this.increment(count); + let res = this.index; + this.index = idx; + return res; + } + + increment(count = 1) { + let dir = count < 0 ? -1 : 1; + count = Math.abs(count); + while (count--) { + this.move(dir); + } + + return this.glyphs[this.index]; + } +} diff --git a/node_modules/fontkit/src/opentype/OTLayoutEngine.js b/node_modules/fontkit/src/opentype/OTLayoutEngine.js new file mode 100644 index 0000000000000000000000000000000000000000..15cf362725a43a0a422eb9d3cd74118d9411a4e6 --- /dev/null +++ b/node_modules/fontkit/src/opentype/OTLayoutEngine.js @@ -0,0 +1,113 @@ +import ShapingPlan from './ShapingPlan'; +import * as Shapers from './shapers'; +import GlyphInfo from './GlyphInfo'; +import GSUBProcessor from './GSUBProcessor'; +import GPOSProcessor from './GPOSProcessor'; + +export default class OTLayoutEngine { + constructor(font) { + this.font = font; + this.glyphInfos = null; + this.plan = null; + this.GSUBProcessor = null; + this.GPOSProcessor = null; + this.fallbackPosition = true; + + if (font.GSUB) { + this.GSUBProcessor = new GSUBProcessor(font, font.GSUB); + } + + if (font.GPOS) { + this.GPOSProcessor = new GPOSProcessor(font, font.GPOS); + } + } + + setup(glyphRun) { + // Map glyphs to GlyphInfo objects so data can be passed between + // GSUB and GPOS without mutating the real (shared) Glyph objects. + this.glyphInfos = glyphRun.glyphs.map(glyph => new GlyphInfo(this.font, glyph.id, [...glyph.codePoints])); + + // Select a script based on what is available in GSUB/GPOS. + let script = null; + if (this.GPOSProcessor) { + script = this.GPOSProcessor.selectScript(glyphRun.script, glyphRun.language, glyphRun.direction); + } + + if (this.GSUBProcessor) { + script = this.GSUBProcessor.selectScript(glyphRun.script, glyphRun.language, glyphRun.direction); + } + + // Choose a shaper based on the script, and setup a shaping plan. + // This determines which features to apply to which glyphs. + this.shaper = Shapers.choose(script); + this.plan = new ShapingPlan(this.font, script, glyphRun.direction); + this.shaper.plan(this.plan, this.glyphInfos, glyphRun.features); + + // Assign chosen features to output glyph run + for (let key in this.plan.allFeatures) { + glyphRun.features[key] = true; + } + } + + substitute(glyphRun) { + if (this.GSUBProcessor) { + this.plan.process(this.GSUBProcessor, this.glyphInfos); + + // Map glyph infos back to normal Glyph objects + glyphRun.glyphs = this.glyphInfos.map(glyphInfo => this.font.getGlyph(glyphInfo.id, glyphInfo.codePoints)); + } + } + + position(glyphRun) { + if (this.shaper.zeroMarkWidths === 'BEFORE_GPOS') { + this.zeroMarkAdvances(glyphRun.positions); + } + + if (this.GPOSProcessor) { + this.plan.process(this.GPOSProcessor, this.glyphInfos, glyphRun.positions); + } + + if (this.shaper.zeroMarkWidths === 'AFTER_GPOS') { + this.zeroMarkAdvances(glyphRun.positions); + } + + // Reverse the glyphs and positions if the script is right-to-left + if (glyphRun.direction === 'rtl') { + glyphRun.glyphs.reverse(); + glyphRun.positions.reverse(); + } + + return this.GPOSProcessor && this.GPOSProcessor.features; + } + + zeroMarkAdvances(positions) { + for (let i = 0; i < this.glyphInfos.length; i++) { + if (this.glyphInfos[i].isMark) { + positions[i].xAdvance = 0; + positions[i].yAdvance = 0; + } + } + } + + cleanup() { + this.glyphInfos = null; + this.plan = null; + this.shaper = null; + } + + getAvailableFeatures(script, language) { + let features = []; + + if (this.GSUBProcessor) { + this.GSUBProcessor.selectScript(script, language); + features.push(...Object.keys(this.GSUBProcessor.features)); + } + + if (this.GPOSProcessor) { + this.GPOSProcessor.selectScript(script, language); + features.push(...Object.keys(this.GPOSProcessor.features)); + } + + return features; + } +} diff --git a/node_modules/fontkit/src/opentype/OTProcessor.js b/node_modules/fontkit/src/opentype/OTProcessor.js new file mode 100644 index 0000000000000000000000000000000000000000..80d1ce69e262575d479bc225ff9d41581bf4b9b4 --- /dev/null +++ b/node_modules/fontkit/src/opentype/OTProcessor.js @@ -0,0 +1,438 @@ +import GlyphIterator from './GlyphIterator'; +import * as Script from '../layout/Script'; + +const DEFAULT_SCRIPTS = ['DFLT', 'dflt', 'latn']; + +export default class OTProcessor { + constructor(font, table) { + this.font = font; + this.table = table; + + this.script = null; + this.scriptTag = null; + + this.language = null; + this.languageTag = null; + + this.features = {}; + this.lookups = {}; + + // Setup variation substitutions + this.variationsIndex = font._variationProcessor + ? this.findVariationsIndex(font._variationProcessor.normalizedCoords) + : -1; + + // initialize to default script + language + this.selectScript(); + + // current context (set by applyFeatures) + this.glyphs = []; + this.positions = []; // only used by GPOS + this.ligatureID = 1; + this.currentFeature = null; + } + + findScript(script) { + if (this.table.scriptList == null) { + return null; + } + + if (!Array.isArray(script)) { + script = [script]; + } + + for (let s of script) { + for (let entry of this.table.scriptList) { + if (entry.tag === s) { + return entry; + } + } + } + + return null; + } + + selectScript(script, language, direction) { + let changed = false; + let entry; + if (!this.script || script !== this.scriptTag) { + entry = this.findScript(script); + if (!entry) { + entry = this.findScript(DEFAULT_SCRIPTS); + } + + if (!entry) { + return this.scriptTag; + } + + this.scriptTag = entry.tag; + this.script = entry.script; + this.language = null; + this.languageTag = null; + changed = true; + } + + if (!direction || direction !== this.direction) { + this.direction = direction || Script.direction(script); + } + + if (language && language.length < 4) { + language += ' '.repeat(4 - language.length); + } + + if (!language || language !== this.languageTag) { + this.language = null; + + for (let lang of this.script.langSysRecords) { + if (lang.tag === language) { + this.language = lang.langSys; + this.languageTag = lang.tag; + break; + } + } + + if (!this.language) { + this.language = this.script.defaultLangSys; + this.languageTag = null; + } + + changed = true; + } + + // Build a feature lookup table + if (changed) { + this.features = {}; + if (this.language) { + for (let featureIndex of this.language.featureIndexes) { + let record = this.table.featureList[featureIndex]; + let substituteFeature = this.substituteFeatureForVariations(featureIndex); + this.features[record.tag] = substituteFeature || record.feature; + } + } + } + + return this.scriptTag; + } + + lookupsForFeatures(userFeatures = [], exclude) { + let lookups = []; + for (let tag of userFeatures) { + let feature = this.features[tag]; + if (!feature) { + continue; + } + + for (let lookupIndex of feature.lookupListIndexes) { + if (exclude && exclude.indexOf(lookupIndex) !== -1) { + continue; + } + + lookups.push({ + feature: tag, + index: lookupIndex, + lookup: this.table.lookupList.get(lookupIndex) + }); + } + } + + lookups.sort((a, b) => a.index - b.index); + return lookups; + } + + substituteFeatureForVariations(featureIndex) { + if (this.variationsIndex === -1) { + return null; + } + + let record = this.table.featureVariations.featureVariationRecords[this.variationsIndex]; + let substitutions = record.featureTableSubstitution.substitutions; + for (let substitution of substitutions) { + if (substitution.featureIndex === featureIndex) { + return substitution.alternateFeatureTable; + } + } + + return null; + } + + findVariationsIndex(coords) { + let variations = this.table.featureVariations; + if (!variations) { + return -1; + } + + let records = variations.featureVariationRecords; + for (let i = 0; i < records.length; i++) { + let conditions = records[i].conditionSet.conditionTable; + if (this.variationConditionsMatch(conditions, coords)) { + return i; + } + } + + return -1; + } + + variationConditionsMatch(conditions, coords) { + return conditions.every(condition => { + let coord = condition.axisIndex < coords.length ? coords[condition.axisIndex] : 0; + return condition.filterRangeMinValue <= coord && coord <= condition.filterRangeMaxValue; + }); + } + + applyFeatures(userFeatures, glyphs, advances) { + let lookups = this.lookupsForFeatures(userFeatures); + this.applyLookups(lookups, glyphs, advances); + } + + applyLookups(lookups, glyphs, positions) { + this.glyphs = glyphs; + this.positions = positions; + this.glyphIterator = new GlyphIterator(glyphs); + + for (let { feature, lookup } of lookups) { + this.currentFeature = feature; + this.glyphIterator.reset(lookup.flags); + + while (this.glyphIterator.index < glyphs.length) { + if (!(feature in this.glyphIterator.cur.features)) { + this.glyphIterator.next(); + continue; + } + + for (let table of lookup.subTables) { + let res = this.applyLookup(lookup.lookupType, table); + if (res) { + break; + } + } + + this.glyphIterator.next(); + } + } + } + + applyLookup(lookup, table) { + throw new Error("applyLookup must be implemented by subclasses"); + } + + applyLookupList(lookupRecords) { + let options = this.glyphIterator.options; + let glyphIndex = this.glyphIterator.index; + + for (let lookupRecord of lookupRecords) { + // Reset flags and find glyph index for this lookup record + this.glyphIterator.reset(options, glyphIndex); + this.glyphIterator.increment(lookupRecord.sequenceIndex); + + // Get the lookup and setup flags for subtables + let lookup = this.table.lookupList.get(lookupRecord.lookupListIndex); + this.glyphIterator.reset(lookup.flags, this.glyphIterator.index); + + // Apply lookup subtables until one matches + for (let table of lookup.subTables) { + if (this.applyLookup(lookup.lookupType, table)) { + break; + } + } + } + + this.glyphIterator.reset(options, glyphIndex); + return true; + } + + coverageIndex(coverage, glyph) { + if (glyph == null) { + glyph = this.glyphIterator.cur.id; + } + + switch (coverage.version) { + case 1: + return coverage.glyphs.indexOf(glyph); + + case 2: + for (let range of coverage.rangeRecords) { + if (range.start <= glyph && glyph <= range.end) { + return range.startCoverageIndex + glyph - range.start; + } + } + + break; + } + + return -1; + } + + match(sequenceIndex, sequence, fn, matched) { + let pos = this.glyphIterator.index; + let glyph = this.glyphIterator.increment(sequenceIndex); + let idx = 0; + + while (idx < sequence.length && glyph && fn(sequence[idx], glyph)) { + if (matched) { + matched.push(this.glyphIterator.index); + } + + idx++; + glyph = this.glyphIterator.next(); + } + + this.glyphIterator.index = pos; + if (idx < sequence.length) { + return false; + } + + return matched || true; + } + + sequenceMatches(sequenceIndex, sequence) { + return this.match(sequenceIndex, sequence, (component, glyph) => component === glyph.id); + } + + sequenceMatchIndices(sequenceIndex, sequence) { + return this.match(sequenceIndex, sequence, (component, glyph) => { + // If the current feature doesn't apply to this glyph, + if (!(this.currentFeature in glyph.features)) { + return false; + } + + return component === glyph.id; + }, []); + } + + coverageSequenceMatches(sequenceIndex, sequence) { + return this.match(sequenceIndex, sequence, (coverage, glyph) => + this.coverageIndex(coverage, glyph.id) >= 0 + ); + } + + getClassID(glyph, classDef) { + switch (classDef.version) { + case 1: // Class array + let i = glyph - classDef.startGlyph; + if (i >= 0 && i < classDef.classValueArray.length) { + return classDef.classValueArray[i]; + } + + break; + + case 2: + for (let range of classDef.classRangeRecord) { + if (range.start <= glyph && glyph <= range.end) { + return range.class; + } + } + + break; + } + + return 0; + } + + classSequenceMatches(sequenceIndex, sequence, classDef) { + return this.match(sequenceIndex, sequence, (classID, glyph) => + classID === this.getClassID(glyph.id, classDef) + ); + } + + applyContext(table) { + let index, set; + switch (table.version) { + case 1: + index = this.coverageIndex(table.coverage); + if (index === -1) { + return false; + } + + set = table.ruleSets[index]; + for (let rule of set) { + if (this.sequenceMatches(1, rule.input)) { + return this.applyLookupList(rule.lookupRecords); + } + } + + break; + + case 2: + if (this.coverageIndex(table.coverage) === -1) { + return false; + } + + index = this.getClassID(this.glyphIterator.cur.id, table.classDef); + if (index === -1) { + return false; + } + + set = table.classSet[index]; + for (let rule of set) { + if (this.classSequenceMatches(1, rule.classes, table.classDef)) { + return this.applyLookupList(rule.lookupRecords); + } + } + + break; + + case 3: + if (this.coverageSequenceMatches(0, table.coverages)) { + return this.applyLookupList(table.lookupRecords); + } + + break; + } + + return false; + } + + applyChainingContext(table) { + let index; + switch (table.version) { + case 1: + index = this.coverageIndex(table.coverage); + if (index === -1) { + return false; + } + + let set = table.chainRuleSets[index]; + for (let rule of set) { + if (this.sequenceMatches(-rule.backtrack.length, rule.backtrack) + && this.sequenceMatches(1, rule.input) + && this.sequenceMatches(1 + rule.input.length, rule.lookahead)) { + return this.applyLookupList(rule.lookupRecords); + } + } + + break; + + case 2: + if (this.coverageIndex(table.coverage) === -1) { + return false; + } + + index = this.getClassID(this.glyphIterator.cur.id, table.inputClassDef); + let rules = table.chainClassSet[index]; + if (!rules) { + return false; + } + + for (let rule of rules) { + if (this.classSequenceMatches(-rule.backtrack.length, rule.backtrack, table.backtrackClassDef) && + this.classSequenceMatches(1, rule.input, table.inputClassDef) && + this.classSequenceMatches(1 + rule.input.length, rule.lookahead, table.lookaheadClassDef)) { + return this.applyLookupList(rule.lookupRecords); + } + } + + break; + + case 3: + if (this.coverageSequenceMatches(-table.backtrackGlyphCount, table.backtrackCoverage) && + this.coverageSequenceMatches(0, table.inputCoverage) && + this.coverageSequenceMatches(table.inputGlyphCount, table.lookaheadCoverage)) { + return this.applyLookupList(table.lookupRecords); + } + + break; + } + + return false; + } +} diff --git a/node_modules/fontkit/src/opentype/ShapingPlan.js b/node_modules/fontkit/src/opentype/ShapingPlan.js new file mode 100644 index 0000000000000000000000000000000000000000..121a7934f45ed3d643b30b05b9ea480856c2a8be --- /dev/null +++ b/node_modules/fontkit/src/opentype/ShapingPlan.js @@ -0,0 +1,118 @@ +import * as Script from '../layout/Script'; + +/** + * ShapingPlans are used by the OpenType shapers to store which + * features should by applied, and in what order to apply them. + * The features are applied in groups called stages. A feature + * can be applied globally to all glyphs, or locally to only + * specific glyphs. + * + * @private + */ +export default class ShapingPlan { + constructor(font, script, direction) { + this.font = font; + this.script = script; + this.direction = direction; + this.stages = []; + this.globalFeatures = {}; + this.allFeatures = {}; + } + + /** + * Adds the given features to the last stage. + * Ignores features that have already been applied. + */ + _addFeatures(features, global) { + let stageIndex = this.stages.length - 1; + let stage = this.stages[stageIndex]; + for (let feature of features) { + if (this.allFeatures[feature] == null) { + stage.push(feature); + this.allFeatures[feature] = stageIndex; + + if (global) { + this.globalFeatures[feature] = true; + } + } + } + } + + /** + * Add features to the last stage + */ + add(arg, global = true) { + if (this.stages.length === 0) { + this.stages.push([]); + } + + if (typeof arg === 'string') { + arg = [arg]; + } + + if (Array.isArray(arg)) { + this._addFeatures(arg, global); + } else if (typeof arg === 'object') { + this._addFeatures(arg.global || [], true); + this._addFeatures(arg.local || [], false); + } else { + throw new Error("Unsupported argument to ShapingPlan#add"); + } + } + + /** + * Add a new stage + */ + addStage(arg, global) { + if (typeof arg === 'function') { + this.stages.push(arg, []); + } else { + this.stages.push([]); + this.add(arg, global); + } + } + + setFeatureOverrides(features) { + if (Array.isArray(features)) { + this.add(features); + } else if (typeof features === 'object') { + for (let tag in features) { + if (features[tag]) { + this.add(tag); + } else if (this.allFeatures[tag] != null) { + let stage = this.stages[this.allFeatures[tag]]; + stage.splice(stage.indexOf(tag), 1); + delete this.allFeatures[tag]; + delete this.globalFeatures[tag]; + } + } + } + } + + /** + * Assigns the global features to the given glyphs + */ + assignGlobalFeatures(glyphs) { + for (let glyph of glyphs) { + for (let feature in this.globalFeatures) { + glyph.features[feature] = true; + } + } + } + + /** + * Executes the planned stages using the given OTProcessor + */ + process(processor, glyphs, positions) { + for (let stage of this.stages) { + if (typeof stage === 'function') { + if (!positions) { + stage(this.font, glyphs, this); + } + + } else if (stage.length > 0) { + processor.applyFeatures(stage, glyphs, positions); + } + } + } +} diff --git a/node_modules/fontkit/src/opentype/shapers/ArabicShaper.js b/node_modules/fontkit/src/opentype/shapers/ArabicShaper.js new file mode 100644 index 0000000000000000000000000000000000000000..fb6d20ef5b5355f7fd6b4650ca4d843453c5ab35 --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/ArabicShaper.js @@ -0,0 +1,123 @@ +import DefaultShaper from './DefaultShaper'; +import {getCategory} from 'unicode-properties'; +import UnicodeTrie from 'unicode-trie'; +import { decodeBase64 } from '../../utils'; + +const trie = new UnicodeTrie(decodeBase64(require('fs').readFileSync(__dirname + '/data.trie', 'base64'))); +const FEATURES = ['isol', 'fina', 'fin2', 'fin3', 'medi', 'med2', 'init']; + +const ShapingClasses = { + Non_Joining: 0, + Left_Joining: 1, + Right_Joining: 2, + Dual_Joining: 3, + Join_Causing: 3, + ALAPH: 4, + 'DALATH RISH': 5, + Transparent: 6 +}; + +const ISOL = 'isol'; +const FINA = 'fina'; +const FIN2 = 'fin2'; +const FIN3 = 'fin3'; +const MEDI = 'medi'; +const MED2 = 'med2'; +const INIT = 'init'; +const NONE = null; + +// Each entry is [prevAction, curAction, nextState] +const STATE_TABLE = [ + // Non_Joining, Left_Joining, Right_Joining, Dual_Joining, ALAPH, DALATH RISH + // State 0: prev was U, not willing to join. + [ [ NONE, NONE, 0 ], [ NONE, ISOL, 2 ], [ NONE, ISOL, 1 ], [ NONE, ISOL, 2 ], [ NONE, ISOL, 1 ], [ NONE, ISOL, 6 ] ], + + // State 1: prev was R or ISOL/ALAPH, not willing to join. + [ [ NONE, NONE, 0 ], [ NONE, ISOL, 2 ], [ NONE, ISOL, 1 ], [ NONE, ISOL, 2 ], [ NONE, FIN2, 5 ], [ NONE, ISOL, 6 ] ], + + // State 2: prev was D/L in ISOL form, willing to join. + [ [ NONE, NONE, 0 ], [ NONE, ISOL, 2 ], [ INIT, FINA, 1 ], [ INIT, FINA, 3 ], [ INIT, FINA, 4 ], [ INIT, FINA, 6 ] ], + + // State 3: prev was D in FINA form, willing to join. + [ [ NONE, NONE, 0 ], [ NONE, ISOL, 2 ], [ MEDI, FINA, 1 ], [ MEDI, FINA, 3 ], [ MEDI, FINA, 4 ], [ MEDI, FINA, 6 ] ], + + // State 4: prev was FINA ALAPH, not willing to join. + [ [ NONE, NONE, 0 ], [ NONE, ISOL, 2 ], [ MED2, ISOL, 1 ], [ MED2, ISOL, 2 ], [ MED2, FIN2, 5 ], [ MED2, ISOL, 6 ] ], + + // State 5: prev was FIN2/FIN3 ALAPH, not willing to join. + [ [ NONE, NONE, 0 ], [ NONE, ISOL, 2 ], [ ISOL, ISOL, 1 ], [ ISOL, ISOL, 2 ], [ ISOL, FIN2, 5 ], [ ISOL, ISOL, 6 ] ], + + // State 6: prev was DALATH/RISH, not willing to join. + [ [ NONE, NONE, 0 ], [ NONE, ISOL, 2 ], [ NONE, ISOL, 1 ], [ NONE, ISOL, 2 ], [ NONE, FIN3, 5 ], [ NONE, ISOL, 6 ] ] +]; + +/** + * This is a shaper for Arabic, and other cursive scripts. + * It uses data from ArabicShaping.txt in the Unicode database, + * compiled to a UnicodeTrie by generate-data.coffee. + * + * The shaping state machine was ported from Harfbuzz. + * https://github.com/behdad/harfbuzz/blob/master/src/hb-ot-shape-complex-arabic.cc + */ +export default class ArabicShaper extends DefaultShaper { + static planFeatures(plan) { + plan.add(['ccmp', 'locl']); + for (let i = 0; i < FEATURES.length; i++) { + let feature = FEATURES[i]; + plan.addStage(feature, false); + } + + plan.addStage('mset'); + } + + static assignFeatures(plan, glyphs) { + super.assignFeatures(plan, glyphs); + + let prev = -1; + let state = 0; + let actions = []; + + // Apply the state machine to map glyphs to features + for (let i = 0; i < glyphs.length; i++) { + let curAction, prevAction; + var glyph = glyphs[i]; + let type = getShapingClass(glyph.codePoints[0]); + if (type === ShapingClasses.Transparent) { + actions[i] = NONE; + continue; + } + + [prevAction, curAction, state] = STATE_TABLE[state][type]; + + if (prevAction !== NONE && prev !== -1) { + actions[prev] = prevAction; + } + + actions[i] = curAction; + prev = i; + } + + // Apply the chosen features to their respective glyphs + for (let index = 0; index < glyphs.length; index++) { + let feature; + var glyph = glyphs[index]; + if (feature = actions[index]) { + glyph.features[feature] = true; + } + } + } +} + +function getShapingClass(codePoint) { + let res = trie.get(codePoint); + if (res) { + return res - 1; + } + + let category = getCategory(codePoint); + if (category === 'Mn' || category === 'Me' || category === 'Cf') { + return ShapingClasses.Transparent; + } + + return ShapingClasses.Non_Joining; +} diff --git a/node_modules/fontkit/src/opentype/shapers/DefaultShaper.js b/node_modules/fontkit/src/opentype/shapers/DefaultShaper.js new file mode 100644 index 0000000000000000000000000000000000000000..e02e4d36d1d96ab7b93e8d56820847ac0c238aad --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/DefaultShaper.js @@ -0,0 +1,72 @@ +import {isDigit} from 'unicode-properties'; + +const VARIATION_FEATURES = ['rvrn']; +const COMMON_FEATURES = ['ccmp', 'locl', 'rlig', 'mark', 'mkmk']; +const FRACTIONAL_FEATURES = ['frac', 'numr', 'dnom']; +const HORIZONTAL_FEATURES = ['calt', 'clig', 'liga', 'rclt', 'curs', 'kern']; +const VERTICAL_FEATURES = ['vert']; +const DIRECTIONAL_FEATURES = { + ltr: ['ltra', 'ltrm'], + rtl: ['rtla', 'rtlm'] +}; + +export default class DefaultShaper { + static zeroMarkWidths = 'AFTER_GPOS'; + static plan(plan, glyphs, features) { + // Plan the features we want to apply + this.planPreprocessing(plan); + this.planFeatures(plan); + this.planPostprocessing(plan, features); + + // Assign the global features to all the glyphs + plan.assignGlobalFeatures(glyphs); + + // Assign local features to glyphs + this.assignFeatures(plan, glyphs); + } + + static planPreprocessing(plan) { + plan.add({ + global: [...VARIATION_FEATURES, ...DIRECTIONAL_FEATURES[plan.direction]], + local: FRACTIONAL_FEATURES + }); + } + + static planFeatures(plan) { + // Do nothing by default. Let subclasses override this. + } + + static planPostprocessing(plan, userFeatures) { + plan.add([...COMMON_FEATURES, ...HORIZONTAL_FEATURES]); + plan.setFeatureOverrides(userFeatures); + } + + static assignFeatures(plan, glyphs) { + // Enable contextual fractions + for (let i = 0; i < glyphs.length; i++) { + let glyph = glyphs[i]; + if (glyph.codePoints[0] === 0x2044) { // fraction slash + let start = i; + let end = i + 1; + + // Apply numerator + while (start > 0 && isDigit(glyphs[start - 1].codePoints[0])) { + glyphs[start - 1].features.numr = true; + glyphs[start - 1].features.frac = true; + start--; + } + + // Apply denominator + while (end < glyphs.length && isDigit(glyphs[end].codePoints[0])) { + glyphs[end].features.dnom = true; + glyphs[end].features.frac = true; + end++; + } + + // Apply fraction slash + glyph.features.frac = true; + i = end - 1; + } + } + } +} diff --git a/node_modules/fontkit/src/opentype/shapers/HangulShaper.js b/node_modules/fontkit/src/opentype/shapers/HangulShaper.js new file mode 100644 index 0000000000000000000000000000000000000000..789fb76f6a9dc6c3075c4a98c7e4979fa0d5b610 --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/HangulShaper.js @@ -0,0 +1,285 @@ +import DefaultShaper from './DefaultShaper'; +import GlyphInfo from '../GlyphInfo'; + +/** + * This is a shaper for the Hangul script, used by the Korean language. + * It does the following: + * - decompose if unsupported by the font: + * -> + * -> + * -> + * + * - compose if supported by the font: + * -> + * -> + * -> + * + * - reorder tone marks (S is any valid syllable): + * -> + * + * - apply ljmo, vjmo, and tjmo OpenType features to decomposed Jamo sequences. + * + * This logic is based on the following documents: + * - http://www.microsoft.com/typography/OpenTypeDev/hangul/intro.htm + * - http://ktug.org/~nomos/harfbuzz-hangul/hangulshaper.pdf + */ +export default class HangulShaper extends DefaultShaper { + static zeroMarkWidths = 'NONE'; + static planFeatures(plan) { + plan.add(['ljmo', 'vjmo', 'tjmo'], false); + } + + static assignFeatures(plan, glyphs) { + let state = 0; + let i = 0; + while (i < glyphs.length) { + let action; + let glyph = glyphs[i]; + let code = glyph.codePoints[0]; + let type = getType(code); + + [ action, state ] = STATE_TABLE[state][type]; + + switch (action) { + case DECOMPOSE: + // Decompose the composed syllable if it is not supported by the font. + if (!plan.font.hasGlyphForCodePoint(code)) { + i = decompose(glyphs, i, plan.font); + } + break; + + case COMPOSE: + // Found a decomposed syllable. Try to compose if supported by the font. + i = compose(glyphs, i, plan.font); + break; + + case TONE_MARK: + // Got a valid syllable, followed by a tone mark. Move the tone mark to the beginning of the syllable. + reorderToneMark(glyphs, i, plan.font); + break; + + case INVALID: + // Tone mark has no valid syllable to attach to, so insert a dotted circle + i = insertDottedCircle(glyphs, i, plan.font); + break; + } + + i++; + } + } +} + +const HANGUL_BASE = 0xac00; +const HANGUL_END = 0xd7a4; +const HANGUL_COUNT = HANGUL_END - HANGUL_BASE + 1; +const L_BASE = 0x1100; // lead +const V_BASE = 0x1161; // vowel +const T_BASE = 0x11a7; // trail +const L_COUNT = 19; +const V_COUNT = 21; +const T_COUNT = 28; +const L_END = L_BASE + L_COUNT - 1; +const V_END = V_BASE + V_COUNT - 1; +const T_END = T_BASE + T_COUNT - 1; +const DOTTED_CIRCLE = 0x25cc; + +const isL = code => 0x1100 <= code && code <= 0x115f || 0xa960 <= code && code <= 0xa97c; +const isV = code => 0x1160 <= code && code <= 0x11a7 || 0xd7b0 <= code && code <= 0xd7c6; +const isT = code => 0x11a8 <= code && code <= 0x11ff || 0xd7cb <= code && code <= 0xd7fb; +const isTone = code => 0x302e <= code && code <= 0x302f; +const isLVT = code => HANGUL_BASE <= code && code <= HANGUL_END; +const isLV = code => (code - HANGUL_BASE) < HANGUL_COUNT && (code - HANGUL_BASE) % T_COUNT === 0; +const isCombiningL = code => L_BASE <= code && code <= L_END; +const isCombiningV = code => V_BASE <= code && code <= V_END; +const isCombiningT = code => T_BASE + 1 && 1 <= code && code <= T_END; + +// Character categories +const X = 0; // Other character +const L = 1; // Leading consonant +const V = 2; // Medial vowel +const T = 3; // Trailing consonant +const LV = 4; // Composed syllable +const LVT = 5; // Composed syllable +const M = 6; // Tone mark + +// This function classifies a character using the above categories. +function getType(code) { + if (isL(code)) { return L; } + if (isV(code)) { return V; } + if (isT(code)) { return T; } + if (isLV(code)) { return LV; } + if (isLVT(code)) { return LVT; } + if (isTone(code)) { return M; } + return X; +} + +// State machine actions +const NO_ACTION = 0; +const DECOMPOSE = 1; +const COMPOSE = 2; +const TONE_MARK = 4; +const INVALID = 5; + +// Build a state machine that accepts valid syllables, and applies actions along the way. +// The logic this is implementing is documented at the top of the file. +const STATE_TABLE = [ + // X L V T LV LVT M + // State 0: start state + [ [ NO_ACTION, 0 ], [ NO_ACTION, 1 ], [ NO_ACTION, 0 ], [ NO_ACTION, 0 ], [ DECOMPOSE, 2 ], [ DECOMPOSE, 3 ], [ INVALID, 0 ] ], + + // State 1: + [ [ NO_ACTION, 0 ], [ NO_ACTION, 1 ], [ COMPOSE, 2 ], [ NO_ACTION, 0 ], [ DECOMPOSE, 2 ], [ DECOMPOSE, 3 ], [ INVALID, 0 ] ], + + // State 2: or + [ [ NO_ACTION, 0 ], [ NO_ACTION, 1 ], [ NO_ACTION, 0 ], [ COMPOSE, 3 ], [ DECOMPOSE, 2 ], [ DECOMPOSE, 3 ], [ TONE_MARK, 0 ] ], + + // State 3: or + [ [ NO_ACTION, 0 ], [ NO_ACTION, 1 ], [ NO_ACTION, 0 ], [ NO_ACTION, 0 ], [ DECOMPOSE, 2 ], [ DECOMPOSE, 3 ], [ TONE_MARK, 0 ] ] +]; + +function getGlyph(font, code, features) { + return new GlyphInfo(font, font.glyphForCodePoint(code).id, [code], features); +} + +function decompose(glyphs, i, font) { + let glyph = glyphs[i]; + let code = glyph.codePoints[0]; + + let s = code - HANGUL_BASE; + let t = T_BASE + s % T_COUNT; + s = s / T_COUNT | 0; + let l = L_BASE + s / V_COUNT | 0; + let v = V_BASE + s % V_COUNT; + + // Don't decompose if all of the components are not available + if (!font.hasGlyphForCodePoint(l) || + !font.hasGlyphForCodePoint(v) || + (t !== T_BASE && !font.hasGlyphForCodePoint(t))) { + return i; + } + + // Replace the current glyph with decomposed L, V, and T glyphs, + // and apply the proper OpenType features to each component. + let ljmo = getGlyph(font, l, glyph.features); + ljmo.features.ljmo = true; + + let vjmo = getGlyph(font, v, glyph.features); + vjmo.features.vjmo = true; + + let insert = [ ljmo, vjmo ]; + + if (t > T_BASE) { + let tjmo = getGlyph(font, t, glyph.features); + tjmo.features.tjmo = true; + insert.push(tjmo); + } + + glyphs.splice(i, 1, ...insert); + return i + insert.length - 1; +} + +function compose(glyphs, i, font) { + let glyph = glyphs[i]; + let code = glyphs[i].codePoints[0]; + let type = getType(code); + + let prev = glyphs[i - 1].codePoints[0]; + let prevType = getType(prev); + + // Figure out what type of syllable we're dealing with + let lv, ljmo, vjmo, tjmo; + if (prevType === LV && type === T) { + // + lv = prev; + tjmo = glyph; + } else { + if (type === V) { + // + ljmo = glyphs[i - 1]; + vjmo = glyph; + } else { + // + ljmo = glyphs[i - 2]; + vjmo = glyphs[i - 1]; + tjmo = glyph; + } + + let l = ljmo.codePoints[0]; + let v = vjmo.codePoints[0]; + + // Make sure L and V are combining characters + if (isCombiningL(l) && isCombiningV(v)) { + lv = HANGUL_BASE + ((l - L_BASE) * V_COUNT + (v - V_BASE)) * T_COUNT; + } + } + + let t = (tjmo && tjmo.codePoints[0]) || T_BASE; + if ((lv != null) && (t === T_BASE || isCombiningT(t))) { + let s = lv + (t - T_BASE); + + // Replace with a composed glyph if supported by the font, + // otherwise apply the proper OpenType features to each component. + if (font.hasGlyphForCodePoint(s)) { + let del = prevType === V ? 3 : 2; + glyphs.splice(i - del + 1, del, getGlyph(font, s, glyph.features)); + return i - del + 1; + } + } + + // Didn't compose (either a non-combining component or unsupported by font). + if (ljmo) { ljmo.features.ljmo = true; } + if (vjmo) { vjmo.features.vjmo = true; } + if (tjmo) { tjmo.features.tjmo = true; } + + if (prevType === LV) { + // Sequence was originally , which got combined earlier. + // Either the T was non-combining, or the LVT glyph wasn't supported. + // Decompose the glyph again and apply OT features. + decompose(glyphs, i - 1, font); + return i + 1; + } + + return i; +} + +function getLength(code) { + switch (getType(code)) { + case LV: + case LVT: + return 1; + case V: + return 2; + case T: + return 3; + } +} + +function reorderToneMark(glyphs, i, font) { + let glyph = glyphs[i]; + let code = glyphs[i].codePoints[0]; + + // Move tone mark to the beginning of the previous syllable, unless it is zero width + if (font.glyphForCodePoint(code).advanceWidth === 0) { return; } + + let prev = glyphs[i - 1].codePoints[0]; + let len = getLength(prev); + + glyphs.splice(i, 1); + return glyphs.splice(i - len, 0, glyph); +} + +function insertDottedCircle(glyphs, i, font) { + let glyph = glyphs[i]; + let code = glyphs[i].codePoints[0]; + + if (font.hasGlyphForCodePoint(DOTTED_CIRCLE)) { + let dottedCircle = getGlyph(font, DOTTED_CIRCLE, glyph.features); + + // If the tone mark is zero width, insert the dotted circle before, otherwise after + let idx = font.glyphForCodePoint(code).advanceWidth === 0 ? i : i + 1; + glyphs.splice(idx, 0, dottedCircle); + i++; + } + + return i; +} diff --git a/node_modules/fontkit/src/opentype/shapers/IndicShaper.js b/node_modules/fontkit/src/opentype/shapers/IndicShaper.js new file mode 100644 index 0000000000000000000000000000000000000000..104198c578e623ccb9cedca0f95d73efd436ef42 --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/IndicShaper.js @@ -0,0 +1,911 @@ +import DefaultShaper from './DefaultShaper'; +import StateMachine from 'dfa'; +import UnicodeTrie from 'unicode-trie'; +import {getCategory} from 'unicode-properties'; +import * as Script from '../../layout/Script'; +import GlyphInfo from '../GlyphInfo'; +import indicMachine from './indic.json'; +import useData from './use.json'; +import { + CATEGORIES, + POSITIONS, + CONSONANT_FLAGS, + JOINER_FLAGS, + HALANT_OR_COENG_FLAGS, INDIC_CONFIGS, + INDIC_DECOMPOSITIONS +} from './indic-data'; +import { decodeBase64 } from '../../utils'; + +const {decompositions} = useData; +const trie = new UnicodeTrie(decodeBase64(require('fs').readFileSync(__dirname + '/indic.trie', 'base64'))); +const stateMachine = new StateMachine(indicMachine); + +/** + * The IndicShaper supports indic scripts e.g. Devanagari, Kannada, etc. + * Based on code from Harfbuzz: https://github.com/behdad/harfbuzz/blob/master/src/hb-ot-shape-complex-indic.cc + */ +export default class IndicShaper extends DefaultShaper { + static zeroMarkWidths = 'NONE'; + static planFeatures(plan) { + plan.addStage(setupSyllables); + + plan.addStage(['locl', 'ccmp']); + + plan.addStage(initialReordering); + + plan.addStage('nukt'); + plan.addStage('akhn'); + plan.addStage('rphf', false); + plan.addStage('rkrf'); + plan.addStage('pref', false); + plan.addStage('blwf', false); + plan.addStage('abvf', false); + plan.addStage('half', false); + plan.addStage('pstf', false); + plan.addStage('vatu'); + plan.addStage('cjct'); + plan.addStage('cfar', false); + + plan.addStage(finalReordering); + + plan.addStage({ + local: ['init'], + global: ['pres', 'abvs', 'blws', 'psts', 'haln', 'dist', 'abvm', 'blwm', 'calt', 'clig'] + }); + + // Setup the indic config for the selected script + plan.unicodeScript = Script.fromOpenType(plan.script); + plan.indicConfig = INDIC_CONFIGS[plan.unicodeScript] || INDIC_CONFIGS.Default; + plan.isOldSpec = plan.indicConfig.hasOldSpec && plan.script[plan.script.length - 1] !== '2'; + + // TODO: turn off kern (Khmer) and liga features. + } + + static assignFeatures(plan, glyphs) { + // Decompose split matras + // TODO: do this in a more general unicode normalizer + for (let i = glyphs.length - 1; i >= 0; i--) { + let codepoint = glyphs[i].codePoints[0]; + let d = INDIC_DECOMPOSITIONS[codepoint] || decompositions[codepoint]; + if (d) { + let decomposed = d.map(c => { + let g = plan.font.glyphForCodePoint(c); + return new GlyphInfo(plan.font, g.id, [c], glyphs[i].features); + }); + + glyphs.splice(i, 1, ...decomposed); + } + } + } +} + +function indicCategory(glyph) { + return trie.get(glyph.codePoints[0]) >> 8; +} + +function indicPosition(glyph) { + return 1 << (trie.get(glyph.codePoints[0]) & 0xff); +} + +class IndicInfo { + constructor(category, position, syllableType, syllable) { + this.category = category; + this.position = position; + this.syllableType = syllableType; + this.syllable = syllable; + } +} + +function setupSyllables(font, glyphs) { + let syllable = 0; + let last = 0; + for (let [start, end, tags] of stateMachine.match(glyphs.map(indicCategory))) { + if (start > last) { + ++syllable; + for (let i = last; i < start; i++) { + glyphs[i].shaperInfo = new IndicInfo(CATEGORIES.X, POSITIONS.End, 'non_indic_cluster', syllable); + } + } + + ++syllable; + + // Create shaper info + for (let i = start; i <= end; i++) { + glyphs[i].shaperInfo = new IndicInfo( + 1 << indicCategory(glyphs[i]), + indicPosition(glyphs[i]), + tags[0], + syllable + ); + } + + last = end + 1; + } + + if (last < glyphs.length) { + ++syllable; + for (let i = last; i < glyphs.length; i++) { + glyphs[i].shaperInfo = new IndicInfo(CATEGORIES.X, POSITIONS.End, 'non_indic_cluster', syllable); + } + } +} + +function isConsonant(glyph) { + return glyph.shaperInfo.category & CONSONANT_FLAGS; +} + +function isJoiner(glyph) { + return glyph.shaperInfo.category & JOINER_FLAGS; +} + +function isHalantOrCoeng(glyph) { + return glyph.shaperInfo.category & HALANT_OR_COENG_FLAGS; +} + +function wouldSubstitute(glyphs, feature) { + for (let glyph of glyphs) { + glyph.features = {[feature]: true}; + } + + let GSUB = glyphs[0]._font._layoutEngine.engine.GSUBProcessor; + GSUB.applyFeatures([feature], glyphs); + + return glyphs.length === 1; +} + +function consonantPosition(font, consonant, virama) { + let glyphs = [virama, consonant, virama]; + if (wouldSubstitute(glyphs.slice(0, 2), 'blwf') || wouldSubstitute(glyphs.slice(1, 3), 'blwf')) { + return POSITIONS.Below_C; + } else if (wouldSubstitute(glyphs.slice(0, 2), 'pstf') || wouldSubstitute(glyphs.slice(1, 3), 'pstf')) { + return POSITIONS.Post_C; + } else if (wouldSubstitute(glyphs.slice(0, 2), 'pref') || wouldSubstitute(glyphs.slice(1, 3), 'pref')) { + return POSITIONS.Post_C; + } + + return POSITIONS.Base_C; +} + +function initialReordering(font, glyphs, plan) { + let indicConfig = plan.indicConfig; + let features = font._layoutEngine.engine.GSUBProcessor.features; + + let dottedCircle = font.glyphForCodePoint(0x25cc).id; + let virama = font.glyphForCodePoint(indicConfig.virama).id; + if (virama) { + let info = new GlyphInfo(font, virama, [indicConfig.virama]); + for (let i = 0; i < glyphs.length; i++) { + if (glyphs[i].shaperInfo.position === POSITIONS.Base_C) { + glyphs[i].shaperInfo.position = consonantPosition(font, glyphs[i].copy(), info); + } + } + } + + for (let start = 0, end = nextSyllable(glyphs, 0); start < glyphs.length; start = end, end = nextSyllable(glyphs, start)) { + let {category, syllableType} = glyphs[start].shaperInfo; + + if (syllableType === 'symbol_cluster' || syllableType === 'non_indic_cluster') { + continue; + } + + if (syllableType === 'broken_cluster' && dottedCircle) { + let g = new GlyphInfo(font, dottedCircle, [0x25cc]); + g.shaperInfo = new IndicInfo( + 1 << indicCategory(g), + indicPosition(g), + glyphs[start].shaperInfo.syllableType, + glyphs[start].shaperInfo.syllable + ); + + // Insert after possible Repha. + let i = start; + while (i < end && glyphs[i].shaperInfo.category === CATEGORIES.Repha) { + i++; + } + + glyphs.splice(i++, 0, g); + end++; + } + + // 1. Find base consonant: + // + // The shaping engine finds the base consonant of the syllable, using the + // following algorithm: starting from the end of the syllable, move backwards + // until a consonant is found that does not have a below-base or post-base + // form (post-base forms have to follow below-base forms), or that is not a + // pre-base reordering Ra, or arrive at the first consonant. The consonant + // stopped at will be the base. + + let base = end; + let limit = start; + let hasReph = false; + + // If the syllable starts with Ra + Halant (in a script that has Reph) + // and has more than one consonant, Ra is excluded from candidates for + // base consonants. + if (indicConfig.rephPos !== POSITIONS.Ra_To_Become_Reph && + features.rphf && + start + 3 <= end && ( + (indicConfig.rephMode === 'Implicit' && !isJoiner(glyphs[start + 2])) || + (indicConfig.rephMode === 'Explicit' && glyphs[start + 2].shaperInfo.category === CATEGORIES.ZWJ) + ) + ) { + // See if it matches the 'rphf' feature. + let g = [glyphs[start].copy(), glyphs[start + 1].copy(), glyphs[start + 2].copy()]; + if (wouldSubstitute(g.slice(0, 2), 'rphf') || (indicConfig.rephMode === 'Explicit' && wouldSubstitute(g, 'rphf'))) { + limit += 2; + while (limit < end && isJoiner(glyphs[limit])) { + limit++; + } + base = start; + hasReph = true; + } + } else if (indicConfig.rephMode === 'Log_Repha' && glyphs[start].shaperInfo.category === CATEGORIES.Repha) { + limit++; + while (limit < end && isJoiner(glyphs[limit])) { + limit++; + } + base = start; + hasReph = true; + } + + switch (indicConfig.basePos) { + case 'Last': { + // starting from the end of the syllable, move backwards + let i = end; + let seenBelow = false; + + do { + let info = glyphs[--i].shaperInfo; + + // until a consonant is found + if (isConsonant(glyphs[i])) { + // that does not have a below-base or post-base form + // (post-base forms have to follow below-base forms), + if (info.position !== POSITIONS.Below_C && (info.position !== POSITIONS.Post_C || seenBelow)) { + base = i; + break; + } + + // or that is not a pre-base reordering Ra, + // + // IMPLEMENTATION NOTES: + // + // Our pre-base reordering Ra's are marked POS_POST_C, so will be skipped + // by the logic above already. + // + + // or arrive at the first consonant. The consonant stopped at will + // be the base. + if (info.position === POSITIONS.Below_C) { + seenBelow = true; + } + + base = i; + } else if (start < i && info.category === CATEGORIES.ZWJ && glyphs[i - 1].shaperInfo.category === CATEGORIES.H) { + // A ZWJ after a Halant stops the base search, and requests an explicit + // half form. + // A ZWJ before a Halant, requests a subjoined form instead, and hence + // search continues. This is particularly important for Bengali + // sequence Ra,H,Ya that should form Ya-Phalaa by subjoining Ya. + break; + } + } while (i > limit); + break; + } + + case 'First': { + // The first consonant is always the base. + base = start; + + // Mark all subsequent consonants as below. + for (let i = base + 1; i < end; i++) { + if (isConsonant(glyphs[i])) { + glyphs[i].shaperInfo.position = POSITIONS.Below_C; + } + } + } + } + + // If the syllable starts with Ra + Halant (in a script that has Reph) + // and has more than one consonant, Ra is excluded from candidates for + // base consonants. + // + // Only do this for unforced Reph. (ie. not for Ra,H,ZWJ) + if (hasReph && base === start && limit - base <= 2) { + hasReph = false; + } + + // 2. Decompose and reorder Matras: + // + // Each matra and any syllable modifier sign in the cluster are moved to the + // appropriate position relative to the consonant(s) in the cluster. The + // shaping engine decomposes two- or three-part matras into their constituent + // parts before any repositioning. Matra characters are classified by which + // consonant in a conjunct they have affinity for and are reordered to the + // following positions: + // + // o Before first half form in the syllable + // o After subjoined consonants + // o After post-form consonant + // o After main consonant (for above marks) + // + // IMPLEMENTATION NOTES: + // + // The normalize() routine has already decomposed matras for us, so we don't + // need to worry about that. + + // 3. Reorder marks to canonical order: + // + // Adjacent nukta and halant or nukta and vedic sign are always repositioned + // if necessary, so that the nukta is first. + // + // IMPLEMENTATION NOTES: + // + // We don't need to do this: the normalize() routine already did this for us. + + // Reorder characters + + for (let i = start; i < base; i++) { + let info = glyphs[i].shaperInfo; + info.position = Math.min(POSITIONS.Pre_C, info.position); + } + + if (base < end) { + glyphs[base].shaperInfo.position = POSITIONS.Base_C; + } + + // Mark final consonants. A final consonant is one appearing after a matra, + // like in Khmer. + for (let i = base + 1; i < end; i++) { + if (glyphs[i].shaperInfo.category === CATEGORIES.M) { + for (let j = i + 1; j < end; j++) { + if (isConsonant(glyphs[j])) { + glyphs[j].shaperInfo.position = POSITIONS.Final_C; + break; + } + } + break; + } + } + + // Handle beginning Ra + if (hasReph) { + glyphs[start].shaperInfo.position = POSITIONS.Ra_To_Become_Reph; + } + + // For old-style Indic script tags, move the first post-base Halant after + // last consonant. + // + // Reports suggest that in some scripts Uniscribe does this only if there + // is *not* a Halant after last consonant already (eg. Kannada), while it + // does it unconditionally in other scripts (eg. Malayalam). We don't + // currently know about other scripts, so we single out Malayalam for now. + // + // Kannada test case: + // U+0C9A,U+0CCD,U+0C9A,U+0CCD + // With some versions of Lohit Kannada. + // https://bugs.freedesktop.org/show_bug.cgi?id=59118 + // + // Malayalam test case: + // U+0D38,U+0D4D,U+0D31,U+0D4D,U+0D31,U+0D4D + // With lohit-ttf-20121122/Lohit-Malayalam.ttf + if (plan.isOldSpec) { + let disallowDoubleHalants = plan.unicodeScript !== 'Malayalam'; + for (let i = base + 1; i < end; i++) { + if (glyphs[i].shaperInfo.category === CATEGORIES.H) { + let j; + for (j = end - 1; j > i; j--) { + if (isConsonant(glyphs[j]) || (disallowDoubleHalants && glyphs[j].shaperInfo.category === CATEGORIES.H)) { + break; + } + } + + if (glyphs[j].shaperInfo.category !== CATEGORIES.H && j > i) { + // Move Halant to after last consonant. + let t = glyphs[i]; + glyphs.splice(i, 0, ...glyphs.splice(i + 1, j - i)); + glyphs[j] = t; + } + + break; + } + } + } + + // Attach misc marks to previous char to move with them. + let lastPos = POSITIONS.Start; + for (let i = start; i < end; i++) { + let info = glyphs[i].shaperInfo; + if (info.category & (JOINER_FLAGS | CATEGORIES.N | CATEGORIES.RS | CATEGORIES.CM | HALANT_OR_COENG_FLAGS & info.category)) { + info.position = lastPos; + if (info.category === CATEGORIES.H && info.position === POSITIONS.Pre_M) { + // Uniscribe doesn't move the Halant with Left Matra. + // TEST: U+092B,U+093F,U+094DE + // We follow. This is important for the Sinhala + // U+0DDA split matra since it decomposes to U+0DD9,U+0DCA + // where U+0DD9 is a left matra and U+0DCA is the virama. + // We don't want to move the virama with the left matra. + // TEST: U+0D9A,U+0DDA + for (let j = i; j > start; j--) { + if (glyphs[j - 1].shaperInfo.position !== POSITIONS.Pre_M) { + info.position = glyphs[j - 1].shaperInfo.position; + break; + } + } + } + } else if (info.position !== POSITIONS.SMVD) { + lastPos = info.position; + } + } + + // For post-base consonants let them own anything before them + // since the last consonant or matra. + let last = base; + for (let i = base + 1; i < end; i++) { + if (isConsonant(glyphs[i])) { + for (let j = last + 1; j < i; j++) { + if (glyphs[j].shaperInfo.position < POSITIONS.SMVD) { + glyphs[j].shaperInfo.position = glyphs[i].shaperInfo.position; + } + } + last = i; + } else if (glyphs[i].shaperInfo.category === CATEGORIES.M) { + last = i; + } + } + + let arr = glyphs.slice(start, end); + arr.sort((a, b) => a.shaperInfo.position - b.shaperInfo.position); + glyphs.splice(start, arr.length, ...arr); + + // Find base again + for (let i = start; i < end; i++) { + if (glyphs[i].shaperInfo.position === POSITIONS.Base_C) { + base = i; + break; + } + } + + // Setup features now + + // Reph + for (let i = start; i < end && glyphs[i].shaperInfo.position === POSITIONS.Ra_To_Become_Reph; i++) { + glyphs[i].features.rphf = true; + } + + // Pre-base + let blwf = !plan.isOldSpec && indicConfig.blwfMode === 'Pre_And_Post'; + for (let i = start; i < base; i++) { + glyphs[i].features.half = true; + if (blwf) { + glyphs[i].features.blwf = true; + } + } + + // Post-base + for (let i = base + 1; i < end; i++) { + glyphs[i].features.abvf = true; + glyphs[i].features.pstf = true; + glyphs[i].features.blwf = true; + } + + if (plan.isOldSpec && plan.unicodeScript === 'Devanagari') { + // Old-spec eye-lash Ra needs special handling. From the + // spec: + // + // "The feature 'below-base form' is applied to consonants + // having below-base forms and following the base consonant. + // The exception is vattu, which may appear below half forms + // as well as below the base glyph. The feature 'below-base + // form' will be applied to all such occurrences of Ra as well." + // + // Test case: U+0924,U+094D,U+0930,U+094d,U+0915 + // with Sanskrit 2003 font. + // + // However, note that Ra,Halant,ZWJ is the correct way to + // request eyelash form of Ra, so we wouldbn't inhibit it + // in that sequence. + // + // Test case: U+0924,U+094D,U+0930,U+094d,U+200D,U+0915 + for (let i = start; i + 1 < base; i++) { + if (glyphs[i].shaperInfo.category === CATEGORIES.Ra && + glyphs[i + 1].shaperInfo.category === CATEGORIES.H && + (i + 1 === base || glyphs[i + 2].shaperInfo.category === CATEGORIES.ZWJ) + ) { + glyphs[i].features.blwf = true; + glyphs[i + 1].features.blwf = true; + } + } + } + + let prefLen = 2; + if (features.pref && base + prefLen < end) { + // Find a Halant,Ra sequence and mark it for pre-base reordering processing. + for (let i = base + 1; i + prefLen - 1 < end; i++) { + let g = [glyphs[i].copy(), glyphs[i + 1].copy()]; + if (wouldSubstitute(g, 'pref')) { + for (let j = 0; j < prefLen; j++) { + glyphs[i++].features.pref = true; + } + + // Mark the subsequent stuff with 'cfar'. Used in Khmer. + // Read the feature spec. + // This allows distinguishing the following cases with MS Khmer fonts: + // U+1784,U+17D2,U+179A,U+17D2,U+1782 + // U+1784,U+17D2,U+1782,U+17D2,U+179A + if (features.cfar) { + for (; i < end; i++) { + glyphs[i].features.cfar = true; + } + } + + break; + } + } + } + + // Apply ZWJ/ZWNJ effects + for (let i = start + 1; i < end; i++) { + if (isJoiner(glyphs[i])) { + let nonJoiner = glyphs[i].shaperInfo.category === CATEGORIES.ZWNJ; + let j = i; + + do { + j--; + + // ZWJ/ZWNJ should disable CJCT. They do that by simply + // being there, since we don't skip them for the CJCT + // feature (ie. F_MANUAL_ZWJ) + + // A ZWNJ disables HALF. + if (nonJoiner) { + delete glyphs[j].features.half; + } + } while (j > start && !isConsonant(glyphs[j])); + } + } + } +} + +function finalReordering(font, glyphs, plan) { + let indicConfig = plan.indicConfig; + let features = font._layoutEngine.engine.GSUBProcessor.features; + + for (let start = 0, end = nextSyllable(glyphs, 0); start < glyphs.length; start = end, end = nextSyllable(glyphs, start)) { + // 4. Final reordering: + // + // After the localized forms and basic shaping forms GSUB features have been + // applied (see below), the shaping engine performs some final glyph + // reordering before applying all the remaining font features to the entire + // cluster. + + let tryPref = !!features.pref; + + // Find base again + let base = start; + for (; base < end; base++) { + if (glyphs[base].shaperInfo.position >= POSITIONS.Base_C) { + if (tryPref && base + 1 < end) { + for (let i = base + 1; i < end; i++) { + if (glyphs[i].features.pref) { + if (!(glyphs[i].substituted && glyphs[i].isLigated && !glyphs[i].isMultiplied)) { + // Ok, this was a 'pref' candidate but didn't form any. + // Base is around here... + base = i; + while (base < end && isHalantOrCoeng(glyphs[base])) { + base++; + } + glyphs[base].shaperInfo.position = POSITIONS.BASE_C; + tryPref = false; + } + break; + } + } + } + + // For Malayalam, skip over unformed below- (but NOT post-) forms. + if (plan.unicodeScript === 'Malayalam') { + for (let i = base + 1; i < end; i++) { + while (i < end && isJoiner(glyphs[i])) { + i++; + } + + if (i === end || !isHalantOrCoeng(glyphs[i])) { + break; + } + + i++; // Skip halant. + while (i < end && isJoiner(glyphs[i])) { + i++; + } + + if (i < end && isConsonant(glyphs[i]) && glyphs[i].shaperInfo.position === POSITIONS.Below_C) { + base = i; + glyphs[base].shaperInfo.position = POSITIONS.Base_C; + } + } + } + + if (start < base && glyphs[base].shaperInfo.position > POSITIONS.Base_C) { + base--; + } + break; + } + } + + if (base === end && start < base && glyphs[base - 1].shaperInfo.category === CATEGORIES.ZWJ) { + base--; + } + + if (base < end) { + while (start < base && glyphs[base].shaperInfo.category & (CATEGORIES.N | HALANT_OR_COENG_FLAGS)) { + base--; + } + } + + // o Reorder matras: + // + // If a pre-base matra character had been reordered before applying basic + // features, the glyph can be moved closer to the main consonant based on + // whether half-forms had been formed. Actual position for the matra is + // defined as “after last standalone halant glyph, after initial matra + // position and before the main consonant”. If ZWJ or ZWNJ follow this + // halant, position is moved after it. + // + + if (start + 1 < end && start < base) { // Otherwise there can't be any pre-base matra characters. + // If we lost track of base, alas, position before last thingy. + let newPos = base === end ? base - 2 : base - 1; + + // Malayalam / Tamil do not have "half" forms or explicit virama forms. + // The glyphs formed by 'half' are Chillus or ligated explicit viramas. + // We want to position matra after them. + if (plan.unicodeScript !== 'Malayalam' && plan.unicodeScript !== 'Tamil') { + while (newPos > start && !(glyphs[newPos].shaperInfo.category & (CATEGORIES.M | HALANT_OR_COENG_FLAGS))) { + newPos--; + } + + // If we found no Halant we are done. + // Otherwise only proceed if the Halant does + // not belong to the Matra itself! + if (isHalantOrCoeng(glyphs[newPos]) && glyphs[newPos].shaperInfo.position !== POSITIONS.Pre_M) { + // If ZWJ or ZWNJ follow this halant, position is moved after it. + if (newPos + 1 < end && isJoiner(glyphs[newPos + 1])) { + newPos++; + } + } else { + newPos = start; // No move. + } + } + + if (start < newPos && glyphs[newPos].shaperInfo.position !== POSITIONS.Pre_M) { + // Now go see if there's actually any matras... + for (let i = newPos; i > start; i--) { + if (glyphs[i - 1].shaperInfo.position === POSITIONS.Pre_M) { + let oldPos = i - 1; + if (oldPos < base && base <= newPos) { // Shouldn't actually happen. + base--; + } + + let tmp = glyphs[oldPos]; + glyphs.splice(oldPos, 0, ...glyphs.splice(oldPos + 1, newPos - oldPos)); + glyphs[newPos] = tmp; + + newPos--; + } + } + } + } + + // o Reorder reph: + // + // Reph’s original position is always at the beginning of the syllable, + // (i.e. it is not reordered at the character reordering stage). However, + // it will be reordered according to the basic-forms shaping results. + // Possible positions for reph, depending on the script, are; after main, + // before post-base consonant forms, and after post-base consonant forms. + + // Two cases: + // + // - If repha is encoded as a sequence of characters (Ra,H or Ra,H,ZWJ), then + // we should only move it if the sequence ligated to the repha form. + // + // - If repha is encoded separately and in the logical position, we should only + // move it if it did NOT ligate. If it ligated, it's probably the font trying + // to make it work without the reordering. + if (start + 1 < end && + glyphs[start].shaperInfo.position === POSITIONS.Ra_To_Become_Reph && + (glyphs[start].shaperInfo.category === CATEGORIES.Repha) !== (glyphs[start].isLigated && !glyphs[start].isMultiplied) + ) { + let newRephPos; + let rephPos = indicConfig.rephPos; + let found = false; + + // 1. If reph should be positioned after post-base consonant forms, + // proceed to step 5. + if (rephPos !== POSITIONS.After_Post) { + // 2. If the reph repositioning class is not after post-base: target + // position is after the first explicit halant glyph between the + // first post-reph consonant and last main consonant. If ZWJ or ZWNJ + // are following this halant, position is moved after it. If such + // position is found, this is the target position. Otherwise, + // proceed to the next step. + // + // Note: in old-implementation fonts, where classifications were + // fixed in shaping engine, there was no case where reph position + // will be found on this step. + newRephPos = start + 1; + while (newRephPos < base && !isHalantOrCoeng(glyphs[newRephPos])) { + newRephPos++; + } + + if (newRephPos < base && isHalantOrCoeng(glyphs[newRephPos])) { + // ->If ZWJ or ZWNJ are following this halant, position is moved after it. + if (newRephPos + 1 < base && isJoiner(glyphs[newRephPos + 1])) { + newRephPos++; + } + + found = true; + } + + // 3. If reph should be repositioned after the main consonant: find the + // first consonant not ligated with main, or find the first + // consonant that is not a potential pre-base reordering Ra. + if (!found && rephPos === POSITIONS.After_Main) { + newRephPos = base; + while (newRephPos + 1 < end && glyphs[newRephPos + 1].shaperInfo.position <= POSITIONS.After_Main) { + newRephPos++; + } + + found = newRephPos < end; + } + + // 4. If reph should be positioned before post-base consonant, find + // first post-base classified consonant not ligated with main. If no + // consonant is found, the target position should be before the + // first matra, syllable modifier sign or vedic sign. + // + // This is our take on what step 4 is trying to say (and failing, BADLY). + if (!found && rephPos === POSITIONS.After_Sub) { + newRephPos = base; + while (newRephPos + 1 < end && !(glyphs[newRephPos + 1].shaperInfo.position & (POSITIONS.Post_C | POSITIONS.After_Post | POSITIONS.SMVD))) { + newRephPos++; + } + + found = newRephPos < end; + } + } + + // 5. If no consonant is found in steps 3 or 4, move reph to a position + // immediately before the first post-base matra, syllable modifier + // sign or vedic sign that has a reordering class after the intended + // reph position. For example, if the reordering position for reph + // is post-main, it will skip above-base matras that also have a + // post-main position. + if (!found) { + // Copied from step 2. + newRephPos = start + 1; + while (newRephPos < base && !isHalantOrCoeng(glyphs[newRephPos])) { + newRephPos++; + } + + if (newRephPos < base && isHalantOrCoeng(glyphs[newRephPos])) { + // ->If ZWJ or ZWNJ are following this halant, position is moved after it. + if (newRephPos + 1 < base && isJoiner(glyphs[newRephPos + 1])) { + newRephPos++; + } + + found = true; + } + } + + // 6. Otherwise, reorder reph to the end of the syllable. + if (!found) { + newRephPos = end - 1; + while (newRephPos > start && glyphs[newRephPos].shaperInfo.position === POSITIONS.SMVD) { + newRephPos--; + } + + // If the Reph is to be ending up after a Matra,Halant sequence, + // position it before that Halant so it can interact with the Matra. + // However, if it's a plain Consonant,Halant we shouldn't do that. + // Uniscribe doesn't do this. + // TEST: U+0930,U+094D,U+0915,U+094B,U+094D + if (isHalantOrCoeng(glyphs[newRephPos])) { + for (let i = base + 1; i < newRephPos; i++) { + if (glyphs[i].shaperInfo.category === CATEGORIES.M) { + newRephPos--; + } + } + } + } + + let reph = glyphs[start]; + glyphs.splice(start, 0, ...glyphs.splice(start + 1, newRephPos - start)); + glyphs[newRephPos] = reph; + + if (start < base && base <= newRephPos) { + base--; + } + } + + // o Reorder pre-base reordering consonants: + // + // If a pre-base reordering consonant is found, reorder it according to + // the following rules: + if (tryPref && base + 1 < end) { + for (let i = base + 1; i < end; i++) { + if (glyphs[i].features.pref) { + // 1. Only reorder a glyph produced by substitution during application + // of the feature. (Note that a font may shape a Ra consonant with + // the feature generally but block it in certain contexts.) + + // Note: We just check that something got substituted. We don't check that + // the feature actually did it... + // + // Reorder pref only if it ligated. + if (glyphs[i].isLigated && !glyphs[i].isMultiplied) { + // 2. Try to find a target position the same way as for pre-base matra. + // If it is found, reorder pre-base consonant glyph. + // + // 3. If position is not found, reorder immediately before main + // consonant. + let newPos = base; + + // Malayalam / Tamil do not have "half" forms or explicit virama forms. + // The glyphs formed by 'half' are Chillus or ligated explicit viramas. + // We want to position matra after them. + if (plan.unicodeScript !== 'Malayalam' && plan.unicodeScript !== 'Tamil') { + while (newPos > start && !(glyphs[newPos - 1].shaperInfo.category & (CATEGORIES.M | HALANT_OR_COENG_FLAGS))) { + newPos--; + } + + // In Khmer coeng model, a H,Ra can go *after* matras. If it goes after a + // split matra, it should be reordered to *before* the left part of such matra. + if (newPos > start && glyphs[newPos - 1].shaperInfo.category === CATEGORIES.M) { + let oldPos = i; + for (let j = base + 1; j < oldPos; j++) { + if (glyphs[j].shaperInfo.category === CATEGORIES.M) { + newPos--; + break; + } + } + } + } + + if (newPos > start && isHalantOrCoeng(glyphs[newPos - 1])) { + // -> If ZWJ or ZWNJ follow this halant, position is moved after it. + if (newPos < end && isJoiner(glyphs[newPos])) { + newPos++; + } + } + + let oldPos = i; + let tmp = glyphs[oldPos]; + glyphs.splice(newPos + 1, 0, ...glyphs.splice(newPos, oldPos - newPos)); + glyphs[newPos] = tmp; + + if (newPos <= base && base < oldPos) { + base++; + } + } + + break; + } + } + } + + // Apply 'init' to the Left Matra if it's a word start. + if (glyphs[start].shaperInfo.position === POSITIONS.Pre_M && (!start || !/Cf|Mn/.test(getCategory(glyphs[start - 1].codePoints[0])))) { + glyphs[start].features.init = true; + } + } +} + +function nextSyllable(glyphs, start) { + if (start >= glyphs.length) return start; + let syllable = glyphs[start].shaperInfo.syllable; + while (++start < glyphs.length && glyphs[start].shaperInfo.syllable === syllable); + return start; +} diff --git a/node_modules/fontkit/src/opentype/shapers/UniversalShaper.js b/node_modules/fontkit/src/opentype/shapers/UniversalShaper.js new file mode 100644 index 0000000000000000000000000000000000000000..3057dd14dec4998714522fdcaee5cebfe7becb6f --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/UniversalShaper.js @@ -0,0 +1,185 @@ +import DefaultShaper from './DefaultShaper'; +import StateMachine from 'dfa'; +import UnicodeTrie from 'unicode-trie'; +import GlyphInfo from '../GlyphInfo'; +import useData from './use.json'; +import { decodeBase64 } from '../../utils'; + +const {categories, decompositions} = useData; +const trie = new UnicodeTrie(decodeBase64(require('fs').readFileSync(__dirname + '/use.trie', 'base64'))); +const stateMachine = new StateMachine(useData); + +/** + * This shaper is an implementation of the Universal Shaping Engine, which + * uses Unicode data to shape a number of scripts without a dedicated shaping engine. + * See https://www.microsoft.com/typography/OpenTypeDev/USE/intro.htm. + */ +export default class UniversalShaper extends DefaultShaper { + static zeroMarkWidths = 'BEFORE_GPOS'; + static planFeatures(plan) { + plan.addStage(setupSyllables); + + // Default glyph pre-processing group + plan.addStage(['locl', 'ccmp', 'nukt', 'akhn']); + + // Reordering group + plan.addStage(clearSubstitutionFlags); + plan.addStage(['rphf'], false); + plan.addStage(recordRphf); + plan.addStage(clearSubstitutionFlags); + plan.addStage(['pref']); + plan.addStage(recordPref); + + // Orthographic unit shaping group + plan.addStage(['rkrf', 'abvf', 'blwf', 'half', 'pstf', 'vatu', 'cjct']); + plan.addStage(reorder); + + // Topographical features + // Scripts that need this are handled by the Arabic shaper, not implemented here for now. + // plan.addStage(['isol', 'init', 'medi', 'fina', 'med2', 'fin2', 'fin3'], false); + + // Standard topographic presentation and positional feature application + plan.addStage(['abvs', 'blws', 'pres', 'psts', 'dist', 'abvm', 'blwm']); + } + + static assignFeatures(plan, glyphs) { + // Decompose split vowels + // TODO: do this in a more general unicode normalizer + for (let i = glyphs.length - 1; i >= 0; i--) { + let codepoint = glyphs[i].codePoints[0]; + if (decompositions[codepoint]) { + let decomposed = decompositions[codepoint].map(c => { + let g = plan.font.glyphForCodePoint(c); + return new GlyphInfo(plan.font, g.id, [c], glyphs[i].features); + }); + + glyphs.splice(i, 1, ...decomposed); + } + } + } +} + +function useCategory(glyph) { + return trie.get(glyph.codePoints[0]); +} + +class USEInfo { + constructor(category, syllableType, syllable) { + this.category = category; + this.syllableType = syllableType; + this.syllable = syllable; + } +} + +function setupSyllables(font, glyphs) { + let syllable = 0; + for (let [start, end, tags] of stateMachine.match(glyphs.map(useCategory))) { + ++syllable; + + // Create shaper info + for (let i = start; i <= end; i++) { + glyphs[i].shaperInfo = new USEInfo(categories[useCategory(glyphs[i])], tags[0], syllable); + } + + // Assign rphf feature + let limit = glyphs[start].shaperInfo.category === 'R' ? 1 : Math.min(3, end - start); + for (let i = start; i < start + limit; i++) { + glyphs[i].features.rphf = true; + } + } +} + +function clearSubstitutionFlags(font, glyphs) { + for (let glyph of glyphs) { + glyph.substituted = false; + } +} + +function recordRphf(font, glyphs) { + for (let glyph of glyphs) { + if (glyph.substituted && glyph.features.rphf) { + // Mark a substituted repha. + glyph.shaperInfo.category = 'R'; + } + } +} + +function recordPref(font, glyphs) { + for (let glyph of glyphs) { + if (glyph.substituted) { + // Mark a substituted pref as VPre, as they behave the same way. + glyph.shaperInfo.category = 'VPre'; + } + } +} + +function reorder(font, glyphs) { + let dottedCircle = font.glyphForCodePoint(0x25cc).id; + + for (let start = 0, end = nextSyllable(glyphs, 0); start < glyphs.length; start = end, end = nextSyllable(glyphs, start)) { + let i, j; + let info = glyphs[start].shaperInfo; + let type = info.syllableType; + + // Only a few syllable types need reordering. + if (type !== 'virama_terminated_cluster' && type !== 'standard_cluster' && type !== 'broken_cluster') { + continue; + } + + // Insert a dotted circle glyph in broken clusters. + if (type === 'broken_cluster' && dottedCircle) { + let g = new GlyphInfo(font, dottedCircle, [0x25cc]); + g.shaperInfo = info; + + // Insert after possible Repha. + for (i = start; i < end && glyphs[i].shaperInfo.category === 'R'; i++); + glyphs.splice(++i, 0, g); + end++; + } + + // Move things forward. + if (info.category === 'R' && end - start > 1) { + // Got a repha. Reorder it to after first base, before first halant. + for (i = start + 1; i < end; i++) { + info = glyphs[i].shaperInfo; + if (isBase(info) || isHalant(glyphs[i])) { + // If we hit a halant, move before it; otherwise it's a base: move to it's + // place, and shift things in between backward. + if (isHalant(glyphs[i])) { + i--; + } + + glyphs.splice(start, 0, ...glyphs.splice(start + 1, i - start), glyphs[i]); + break; + } + } + } + + // Move things back. + for (i = start, j = end; i < end; i++) { + info = glyphs[i].shaperInfo; + if (isBase(info) || isHalant(glyphs[i])) { + // If we hit a halant, move after it; otherwise it's a base: move to it's + // place, and shift things in between backward. + j = isHalant(glyphs[i]) ? i + 1 : i; + } else if ((info.category === 'VPre' || info.category === 'VMPre') && j < i) { + glyphs.splice(j, 1, glyphs[i], ...glyphs.splice(j, i - j)); + } + } + } +} + +function nextSyllable(glyphs, start) { + if (start >= glyphs.length) return start; + let syllable = glyphs[start].shaperInfo.syllable; + while (++start < glyphs.length && glyphs[start].shaperInfo.syllable === syllable); + return start; +} + +function isHalant(glyph) { + return glyph.shaperInfo.category === 'H' && !glyph.isLigated; +} + +function isBase(info) { + return info.category === 'B' || info.category === 'GB'; +} diff --git a/node_modules/fontkit/src/opentype/shapers/data.trie b/node_modules/fontkit/src/opentype/shapers/data.trie new file mode 100644 index 0000000000000000000000000000000000000000..14e3519e93d2b42fbd1a70c2ca131a3eedb07e29 Binary files /dev/null and b/node_modules/fontkit/src/opentype/shapers/data.trie differ diff --git a/node_modules/fontkit/src/opentype/shapers/gen-indic.js b/node_modules/fontkit/src/opentype/shapers/gen-indic.js new file mode 100644 index 0000000000000000000000000000000000000000..7cd398945178ea5ff906932c803d5440a02c592b --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/gen-indic.js @@ -0,0 +1,208 @@ +import codepoints from 'codepoints'; +import fs from 'fs'; +import UnicodeTrieBuilder from 'unicode-trie/builder.js'; +import dfa from 'dfa/compile.js'; +import { CATEGORIES, POSITIONS, CONSONANT_FLAGS } from './indic-data.js'; + +const compile = dfa.default; + +const CATEGORY_MAP = { + Avagraha: 'Symbol', + Bindu: 'SM', + Brahmi_Joining_Number: 'Placeholder', + Cantillation_Mark: 'A', + Consonant: 'C', + Consonant_Dead: 'C', + Consonant_Final: 'CM', + Consonant_Head_Letter: 'C', + Consonant_Killer: 'M', + Consonant_Medial: 'CM', + Consonant_Placeholder: 'Placeholder', + Consonant_Preceding_Repha: 'Repha', + Consonant_Prefixed: 'X', + Consonant_Subjoined: 'CM', + Consonant_Succeeding_Repha: 'N', + Consonant_With_Stacker: 'Repha', + Gemination_Mark: 'SM', + Invisible_Stacker: 'Coeng', + Joiner: 'ZWJ', + Modifying_Letter: 'X', + Non_Joiner: 'ZWNJ', + Nukta: 'N', + Number: 'Placeholder', + Number_Joiner: 'Placeholder', + Pure_Killer: 'M', + Register_Shifter: 'RS', + Syllable_Modifier: 'M', + Tone_Letter: 'X', + Tone_Mark: 'N', + Virama: 'H', + Visarga: 'SM', + Vowel: 'V', + Vowel_Dependent: 'M', + Vowel_Independent: 'V' +}; + +const OVERRIDES = { + 0x0953: 'SM', + 0x0954: 'SM', + 0x0A72: 'C', + 0x0A73: 'C', + 0x1CF5: 'C', + 0x1CF6: 'C', + 0x1CE2: 'A', + 0x1CE3: 'A', + 0x1CE4: 'A', + 0x1CE5: 'A', + 0x1CE6: 'A', + 0x1CE7: 'A', + 0x1CE8: 'A', + 0x1CED: 'A', + 0xA8F2: 'Symbol', + 0xA8F3: 'Symbol', + 0xA8F4: 'Symbol', + 0xA8F5: 'Symbol', + 0xA8F6: 'Symbol', + 0xA8F7: 'Symbol', + 0x1CE9: 'Symbol', + 0x1CEA: 'Symbol', + 0x1CEB: 'Symbol', + 0x1CEC: 'Symbol', + 0x1CEE: 'Symbol', + 0x1CEF: 'Symbol', + 0x1CF0: 'Symbol', + 0x1CF1: 'Symbol', + 0x17C6: 'N', + 0x2010: 'Placeholder', + 0x2011: 'Placeholder', + 0x25CC: 'Dotted_Circle', + + // Ra + 0x0930: 'Ra', // Devanagari + 0x09B0: 'Ra', // Bengali + 0x09F0: 'Ra', // Bengali + 0x0A30: 'Ra', // Gurmukhi - No Reph + 0x0AB0: 'Ra', // Gujarati + 0x0B30: 'Ra', // Oriya + 0x0BB0: 'Ra', // Tamil - No Reph + 0x0C30: 'Ra', // Telugu - Reph formed only with ZWJ + 0x0CB0: 'Ra', // Kannada + 0x0D30: 'Ra', // Malayalam - No Reph, Logical Repha + 0x0DBB: 'Ra', // Sinhala - Reph formed only with ZWJ + 0x179A: 'Ra', // Khmer - No Reph, Visual Repha +}; + +const POSITION_MAP = { + Left: 'Pre_C', + Top: 'Above_C', + Bottom: 'Below_C', + Right: 'Post_C', + + // These should resolve to the position of the last part of the split sequence. + Bottom_And_Right: 'Post_C', + Left_And_Right: 'Post_C', + Top_And_Bottom: 'Below_C', + Top_And_Bottom_And_Right: 'Post_C', + Top_And_Left: 'Above_C', + Top_And_Left_And_Right: 'Post_C', + Top_And_Right: 'Post_C', + + Overstruck: 'After_Main', + Visual_Order_Left: 'Pre_M' +}; + +function matraPosition(c, pos) { + switch (pos) { + case 'Pre_C': + return 'Pre_M'; + + case 'Post_C': + switch (c.block) { + case 'Devanagari': return 'After_Sub'; + case 'Bengali': return 'After_Post'; + case 'Gurmukhi': return 'After_Post'; + case 'Gujarati': return 'After_Post'; + case 'Oriya': return 'After_Post'; + case 'Tamil': return 'After_Post'; + case 'Telugu': return c.code <= 0x0C42 ? 'Before_Sub' : 'After_Sub'; + case 'Kannada': return c.code < 0x0CC3 || c.code > 0xCD6 ? 'Before_Sub' : 'After_Sub'; + case 'Malayalam': return 'After_Post'; + case 'Sinhala': return 'After_Sub'; + case 'Khmer': return 'After_Post'; + default: return 'After_Sub'; + } + + case 'Above_C': + switch (c.block) { + case 'Devanagari': return 'After_Sub'; + case 'Gurmukhi': return 'After_Post'; // Deviate from spec + case 'Gujarati': return 'After_Sub'; + case 'Oriya': return 'After_Main'; + case 'Tamil': return 'After_Sub'; + case 'Telugu': return 'Before_Sub'; + case 'Kannada': return 'Before_Sub'; + case 'Sinhala': return 'After_Sub'; + case 'Khmer': return 'After_Post'; + default: return 'After_Sub'; + } + + case 'Below_C': + switch (c.block) { + case 'Devanagari': return 'After_Sub'; + case 'Bengali': return 'After_Sub'; + case 'Gurmukhi': return 'After_Post'; + case 'Gujarati': return 'After_Post'; + case 'Oriya': return 'After_Sub'; + case 'Tamil': return 'After_Post'; + case 'Telugu': return 'Before_Sub'; + case 'Kannada': return 'Before_Sub'; + case 'Malayalam': return 'After_Post'; + case 'Sinhala': return 'After_Sub'; + case 'Khmer': return 'After_Post'; + default: return 'After_Sub'; + } + + default: + return pos; + } +} + +function getPosition(codepoint, category) { + let position = POSITION_MAP[codepoint.indicPositionalCategory] || 'End'; + + if (CATEGORIES[category] & CONSONANT_FLAGS) { + position = 'Base_C'; + } else if (category === 'M') { + position = matraPosition(codepoint, position); + } else if (category === 'SM' || category === 'VD' || category === 'A' || category === 'Symbol') { + position = 'SMVD'; + } + + // Oriya Bindu is Before_Sub in the spec. + if (codepoint.code === 0x0B01) { + position = 'Before_Sub'; + } + + return Math.log2(POSITIONS[position]); +} + +let symbols = {}; +for (let c in CATEGORIES) { + symbols[c] = Math.log2(CATEGORIES[c]); +} + +let trie = new UnicodeTrieBuilder; +for (let i = 0; i < codepoints.length; i++) { + let codepoint = codepoints[i]; + if (codepoint) { + let category = OVERRIDES[codepoint.code] || CATEGORY_MAP[codepoint.indicSyllabicCategory] || 'X'; + let position = getPosition(codepoint, category); + + trie.set(codepoint.code, (symbols[category] << 8) | position); + } +} + +fs.writeFileSync(new URL('indic.trie', import.meta.url), trie.toBuffer()); + +let stateMachine = compile(fs.readFileSync(new URL('indic.machine', import.meta.url), 'utf8'), symbols); +fs.writeFileSync(new URL('indic.json', import.meta.url), JSON.stringify(stateMachine)); diff --git a/node_modules/fontkit/src/opentype/shapers/gen-use.js b/node_modules/fontkit/src/opentype/shapers/gen-use.js new file mode 100644 index 0000000000000000000000000000000000000000..cb7eda55ad5845cf6b0681e2ffa1e947b01075ef --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/gen-use.js @@ -0,0 +1,287 @@ +import codepoints from 'codepoints'; +import fs from 'fs'; +import UnicodeTrieBuilder from 'unicode-trie/builder.js'; +import dfa from 'dfa/compile.js'; + +const compile = dfa.default; + +const CATEGORIES = { + B: [ + {UISC: 'Number'}, + {UISC: 'Avagraha', UGC: 'Lo'}, + {UISC: 'Bindu', UGC: 'Lo'}, + {UISC: 'Consonant'}, + {UISC: 'Consonant_Final', UGC: 'Lo'}, + {UISC: 'Consonant_Head_Letter'}, + {UISC: 'Consonant_Medial', UGC: 'Lo'}, + {UISC: 'Consonant_Subjoined', UGC: 'Lo'}, + {UISC: 'Tone_Letter'}, + {UISC: 'Vowel', UGC: 'Lo'}, + {UISC: 'Vowel_Independent'}, + {UISC: 'Vowel_Dependent', UGC: 'Lo'} + ], + CGJ: [0x034f], + CM: [ + 'Nukta', + 'Gemination_Mark', + 'Consonant_Killer' + ], + CS: [ + 'Consonant_With_Stacker' + ], + F: [ + {UISC: 'Consonant_Final', UGC: {not: 'Lo'}}, + {UISC: 'Consonant_Succeeding_Repha'} + ], + FM: [ + 'Syllable_Modifier' + ], + GB: [ + 'Consonant_Placeholder', + 0x2015, + 0x2022, + 0x25fb, + 0x25fc, + 0x25fd, + 0x25fe + ], + H: [ + 'Virama', + 'Invisible_Stacker' + ], + HN: [ + 'Number_Joiner' + ], + IND: [ + 'Consonant_Dead', + 'Modifying_Letter', + {UGC: 'Po', U: {not: [0x104e, 0x2022]}} + ], + M: [ + {UISC: 'Consonant_Medial', UGC: {not: 'Lo'}} + ], + N: [ + 'Brahmi_Joining_Number' + ], + R: [ + 'Consonant_Preceding_Repha', + 'Consonant_Prefixed' + ], + Rsv: [ + {UGC: 'Cn'} // TODO + ], + S: [ + {UGC: 'So', U: {not: 0x25cc}}, + {UGC: 'Sc'} + ], + SM: [ + 0x1b6b, + 0x1b6c, + 0x1b6d, + 0x1b6e, + 0x1b6f, + 0x1b70, + 0x1b71, + 0x1b72, + 0x1b73 + ], + SUB: [ + {UISC: 'Consonant_Subjoined', UGC: {not: 'Lo'}} + ], + V: [ + {UISC: 'Vowel', UGC: {not: 'Lo'}}, + {UISC: 'Vowel_Dependent', UGC: {not: 'Lo'}}, + {UISC: 'Pure_Killer'} + ], + VM: [ + {UISC: 'Bindu', UGC: {not: 'Lo'}}, + 'Tone_Mark', + 'Cantillation_Mark', + 'Register_Shifter', + 'Visarga' + ], + VS: [ + 0xfe00, 0xfe01, 0xfe02, 0xfe03, 0xfe04, 0xfe05, 0xfe06, 0xfe07, + 0xfe08, 0xfe09, 0xfe0a, 0xfe0b, 0xfe0c, 0xfe0d, 0xfe0e, 0xfe0f + ], + WJ: [0x2060], + ZWJ: [ + 'Joiner' + ], + ZWNJ: [ + 'Non_Joiner' + ], + O: [ + 'Other' + ] +}; + +const USE_POSITIONS = { + F: { + Abv: ['Top'], + Blw: ['Bottom'], + Pst: ['Right'], + }, + M: { + Abv: ['Top'], + Blw: ['Bottom'], + Pst: ['Right'], + Pre: ['Left'], + }, + CM: { + Abv: ['Top'], + Blw: ['Bottom'], + }, + V: { + Abv: ['Top', 'Top_And_Bottom', 'Top_And_Bottom_And_Right', 'Top_And_Right'], + Blw: ['Bottom', 'Overstruck', 'Bottom_And_Right'], + Pst: ['Right'], + Pre: ['Left', 'Top_And_Left', 'Top_And_Left_And_Right', 'Left_And_Right'], + }, + VM: { + Abv: ['Top'], + Blw: ['Bottom', 'Overstruck'], + Pst: ['Right'], + Pre: ['Left'], + }, + SM: { + Abv: ['Top'], + Blw: ['Bottom'], + } +}; + +const UISC_OVERRIDE = { + 0x17dd: 'Vowel_Dependent', + 0x1ce2: 'Cantillation_Mark', + 0x1ce3: 'Cantillation_Mark', + 0x1ce4: 'Cantillation_Mark', + 0x1ce5: 'Cantillation_Mark', + 0x1ce6: 'Cantillation_Mark', + 0x1ce7: 'Cantillation_Mark', + 0x1ce8: 'Cantillation_Mark', + 0x1ced: 'Tone_Mark' +}; + +const UIPC_OVERRIDE = { + 0x1b6c: 'Bottom', + 0x953: 'Not_Applicable', + 0x954: 'Not_Applicable', + 0x103c: 'Left', + 0xa926: 'Top', + 0xa927: 'Top', + 0xa928: 'Top', + 0xa929: 'Top', + 0xa92a: 'Top', + 0x111ca: 'Bottom', + 0x11300: 'Top', + 0x1133c: 'Bottom', + 0x1171e: 'Left', + 0x1cf2: 'Right', + 0x1cf3: 'Right', + 0x1cf8: 'Top', + 0x1cf9: 'Top' +}; + +function check(pattern, value) { + if (typeof pattern === 'object' && pattern.not) { + if (Array.isArray(pattern.not)) { + return pattern.not.indexOf(value) === -1; + } else { + return value !== pattern.not; + } + } + + return value === pattern; +} + +function matches(pattern, code) { + if (typeof pattern === 'number') { + pattern = {U: pattern}; + } else if (typeof pattern === 'string') { + pattern = {UISC: pattern}; + } + + for (let key in pattern) { + if (!check(pattern[key], code[key])) { + return false; + } + } + + return true; +} + +function getUISC(code) { + return UISC_OVERRIDE[code.code] || code.indicSyllabicCategory || 'Other'; +} + +function getUIPC(code) { + return UIPC_OVERRIDE[code.code] || code.indicPositionalCategory; +} + +function getPositionalCategory(code, USE) { + let UIPC = getUIPC(code); + let pos = USE_POSITIONS[USE]; + if (pos) { + for (let key in pos) { + if (pos[key].indexOf(UIPC) !== -1) { + return USE + key; + } + } + } + + return USE; +} + +function getCategory(code) { + for (let category in CATEGORIES) { + for (let pattern of CATEGORIES[category]) { + if (matches(pattern, {UISC: getUISC(code), UGC: code.category, U: code.code})) { + return getPositionalCategory(code, category); + } + } + } + + return null; +} + +let trie = new UnicodeTrieBuilder; +let symbols = {}; +let numSymbols = 0; +let decompositions = {}; +for (let i = 0; i < codepoints.length; i++) { + let codepoint = codepoints[i]; + if (codepoint) { + let category = getCategory(codepoint); + if (!(category in symbols)) { + symbols[category] = numSymbols++; + } + + trie.set(codepoint.code, symbols[category]); + + if (codepoint.indicSyllabicCategory === 'Vowel_Dependent' && codepoint.decomposition.length > 0) { + decompositions[codepoint.code] = decompose(codepoint.code); + } + } +} + +function decompose(code) { + let decomposition = []; + let codepoint = codepoints[code]; + for (let c of codepoint.decomposition) { + let codes = decompose(c); + codes = codes.length > 0 ? codes : [c]; + decomposition.push(...codes); + } + + return decomposition; +} + +fs.writeFileSync(new URL('use.trie', import.meta.url), trie.toBuffer()); + +let stateMachine = compile(fs.readFileSync(new URL('use.machine', import.meta.url), 'utf8'), symbols); +let json = Object.assign({ + categories: Object.keys(symbols), + decompositions: decompositions +}, stateMachine); + +fs.writeFileSync(new URL('use.json', import.meta.url), JSON.stringify(json)); diff --git a/node_modules/fontkit/src/opentype/shapers/generate-data.js b/node_modules/fontkit/src/opentype/shapers/generate-data.js new file mode 100644 index 0000000000000000000000000000000000000000..e8ad55b9e2d63043359773032f52af7240663e75 --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/generate-data.js @@ -0,0 +1,33 @@ +// +// This script generates a UnicodeTrie containing shaping data derived +// from Unicode properties (currently just for the Arabic shaper). +// +import codepoints from 'codepoints'; +import fs from 'fs'; +import UnicodeTrieBuilder from 'unicode-trie/builder.js'; + +let ShapingClasses = { + Non_Joining: 0, + Left_Joining: 1, + Right_Joining: 2, + Dual_Joining: 3, + Join_Causing: 3, + ALAPH: 4, + 'DALATH RISH': 5, + Transparent: 6 +}; + +let trie = new UnicodeTrieBuilder; +for (let i = 0; i < codepoints.length; i++) { + let codepoint = codepoints[i]; + if (codepoint) { + if (codepoint.joiningGroup === 'ALAPH' || codepoint.joiningGroup === 'DALATH RISH') { + trie.set(codepoint.code, ShapingClasses[codepoint.joiningGroup] + 1); + + } else if (codepoint.joiningType) { + trie.set(codepoint.code, ShapingClasses[codepoint.joiningType] + 1); + } + } +} + +fs.writeFileSync(new URL('data.trie', import.meta.url), trie.toBuffer()); diff --git a/node_modules/fontkit/src/opentype/shapers/index.js b/node_modules/fontkit/src/opentype/shapers/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b22ebdd3e256e693eb4ce009920ee9607c3ba48d --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/index.js @@ -0,0 +1,102 @@ +import DefaultShaper from './DefaultShaper'; +import ArabicShaper from './ArabicShaper'; +import HangulShaper from './HangulShaper'; +import IndicShaper from './IndicShaper'; +import UniversalShaper from './UniversalShaper'; + +const SHAPERS = { + arab: ArabicShaper, // Arabic + mong: ArabicShaper, // Mongolian + syrc: ArabicShaper, // Syriac + 'nko ': ArabicShaper, // N'Ko + phag: ArabicShaper, // Phags Pa + mand: ArabicShaper, // Mandaic + mani: ArabicShaper, // Manichaean + phlp: ArabicShaper, // Psalter Pahlavi + + hang: HangulShaper, // Hangul + + bng2: IndicShaper, // Bengali + beng: IndicShaper, // Bengali + dev2: IndicShaper, // Devanagari + deva: IndicShaper, // Devanagari + gjr2: IndicShaper, // Gujarati + gujr: IndicShaper, // Gujarati + guru: IndicShaper, // Gurmukhi + gur2: IndicShaper, // Gurmukhi + knda: IndicShaper, // Kannada + knd2: IndicShaper, // Kannada + mlm2: IndicShaper, // Malayalam + mlym: IndicShaper, // Malayalam + ory2: IndicShaper, // Oriya + orya: IndicShaper, // Oriya + taml: IndicShaper, // Tamil + tml2: IndicShaper, // Tamil + telu: IndicShaper, // Telugu + tel2: IndicShaper, // Telugu + khmr: IndicShaper, // Khmer + + bali: UniversalShaper, // Balinese + batk: UniversalShaper, // Batak + brah: UniversalShaper, // Brahmi + bugi: UniversalShaper, // Buginese + buhd: UniversalShaper, // Buhid + cakm: UniversalShaper, // Chakma + cham: UniversalShaper, // Cham + dupl: UniversalShaper, // Duployan + egyp: UniversalShaper, // Egyptian Hieroglyphs + gran: UniversalShaper, // Grantha + hano: UniversalShaper, // Hanunoo + java: UniversalShaper, // Javanese + kthi: UniversalShaper, // Kaithi + kali: UniversalShaper, // Kayah Li + khar: UniversalShaper, // Kharoshthi + khoj: UniversalShaper, // Khojki + sind: UniversalShaper, // Khudawadi + lepc: UniversalShaper, // Lepcha + limb: UniversalShaper, // Limbu + mahj: UniversalShaper, // Mahajani + // mand: UniversalShaper, // Mandaic + // mani: UniversalShaper, // Manichaean + mtei: UniversalShaper, // Meitei Mayek + modi: UniversalShaper, // Modi + // mong: UniversalShaper, // Mongolian + // 'nko ': UniversalShaper, // N’Ko + hmng: UniversalShaper, // Pahawh Hmong + // phag: UniversalShaper, // Phags-pa + // phlp: UniversalShaper, // Psalter Pahlavi + rjng: UniversalShaper, // Rejang + saur: UniversalShaper, // Saurashtra + shrd: UniversalShaper, // Sharada + sidd: UniversalShaper, // Siddham + sinh: IndicShaper, // Sinhala + sund: UniversalShaper, // Sundanese + sylo: UniversalShaper, // Syloti Nagri + tglg: UniversalShaper, // Tagalog + tagb: UniversalShaper, // Tagbanwa + tale: UniversalShaper, // Tai Le + lana: UniversalShaper, // Tai Tham + tavt: UniversalShaper, // Tai Viet + takr: UniversalShaper, // Takri + tibt: UniversalShaper, // Tibetan + tfng: UniversalShaper, // Tifinagh + tirh: UniversalShaper, // Tirhuta + + latn: DefaultShaper, // Latin + DFLT: DefaultShaper // Default +}; + +export function choose(script) { + if (!Array.isArray(script)) { + script = [script]; + } + + for (let s of script) { + let shaper = SHAPERS[s]; + if (shaper) { + return shaper; + } + } + + return DefaultShaper; +} diff --git a/node_modules/fontkit/src/opentype/shapers/indic-data.js b/node_modules/fontkit/src/opentype/shapers/indic-data.js new file mode 100644 index 0000000000000000000000000000000000000000..30feff2b8d031a825d559c109f2938599c61e71a --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/indic-data.js @@ -0,0 +1,175 @@ +// Cateories used in the OpenType spec: +// https://www.microsoft.com/typography/otfntdev/devanot/shaping.aspx +export const CATEGORIES = { + X: 1 << 0, + C: 1 << 1, + V: 1 << 2, + N: 1 << 3, + H: 1 << 4, + ZWNJ: 1 << 5, + ZWJ: 1 << 6, + M: 1 << 7, + SM: 1 << 8, + VD: 1 << 9, + A: 1 << 10, + Placeholder: 1 << 11, + Dotted_Circle: 1 << 12, + RS: 1 << 13, // Register Shifter, used in Khmer OT spec. + Coeng: 1 << 14, // Khmer-style Virama. + Repha: 1 << 15, // Atomically-encoded logical or visual repha. + Ra: 1 << 16, + CM: 1 << 17, // Consonant-Medial. + Symbol: 1 << 18 // Avagraha, etc that take marks (SM,A,VD). +}; + +// Visual positions in a syllable from left to right. +export const POSITIONS = { + Start: 1 << 0, + + Ra_To_Become_Reph: 1 << 1, + Pre_M: 1 << 2, + Pre_C: 1 << 3, + + Base_C: 1 << 4, + After_Main: 1 << 5, + + Above_C: 1 << 6, + + Before_Sub: 1 << 7, + Below_C: 1 << 8, + After_Sub: 1 << 9, + + Before_Post: 1 << 10, + Post_C: 1 << 11, + After_Post: 1 << 12, + + Final_C: 1 << 13, + SMVD: 1 << 14, + + End: 1 << 15 +}; + +export const CONSONANT_FLAGS = CATEGORIES.C | CATEGORIES.Ra | CATEGORIES.CM | CATEGORIES.V | CATEGORIES.Placeholder | CATEGORIES.Dotted_Circle; +export const JOINER_FLAGS = CATEGORIES.ZWJ | CATEGORIES.ZWNJ; +export const HALANT_OR_COENG_FLAGS = CATEGORIES.H | CATEGORIES.Coeng; + +export const INDIC_CONFIGS = { + Default: { + hasOldSpec: false, + virama: 0, + basePos: 'Last', + rephPos: POSITIONS.Before_Post, + rephMode: 'Implicit', + blwfMode: 'Pre_And_Post' + }, + + Devanagari: { + hasOldSpec: true, + virama: 0x094D, + basePos: 'Last', + rephPos: POSITIONS.Before_Post, + rephMode: 'Implicit', + blwfMode: 'Pre_And_Post' + }, + + Bengali: { + hasOldSpec: true, + virama: 0x09CD, + basePos: 'Last', + rephPos: POSITIONS.After_Sub, + rephMode: 'Implicit', + blwfMode: 'Pre_And_Post' + }, + + Gurmukhi: { + hasOldSpec: true, + virama: 0x0A4D, + basePos: 'Last', + rephPos: POSITIONS.Before_Sub, + rephMode: 'Implicit', + blwfMode: 'Pre_And_Post' + }, + + Gujarati: { + hasOldSpec: true, + virama: 0x0ACD, + basePos: 'Last', + rephPos: POSITIONS.Before_Post, + rephMode: 'Implicit', + blwfMode: 'Pre_And_Post' + }, + + Oriya: { + hasOldSpec: true, + virama: 0x0B4D, + basePos: 'Last', + rephPos: POSITIONS.After_Main, + rephMode: 'Implicit', + blwfMode: 'Pre_And_Post' + }, + + Tamil: { + hasOldSpec: true, + virama: 0x0BCD, + basePos: 'Last', + rephPos: POSITIONS.After_Post, + rephMode: 'Implicit', + blwfMode: 'Pre_And_Post' + }, + + Telugu: { + hasOldSpec: true, + virama: 0x0C4D, + basePos: 'Last', + rephPos: POSITIONS.After_Post, + rephMode: 'Explicit', + blwfMode: 'Post_Only' + }, + + Kannada: { + hasOldSpec: true, + virama: 0x0CCD, + basePos: 'Last', + rephPos: POSITIONS.After_Post, + rephMode: 'Implicit', + blwfMode: 'Post_Only' + }, + + Malayalam: { + hasOldSpec: true, + virama: 0x0D4D, + basePos: 'Last', + rephPos: POSITIONS.After_Main, + rephMode: 'Log_Repha', + blwfMode: 'Pre_And_Post' + }, + + // Handled by UniversalShaper + // Sinhala: { + // hasOldSpec: false, + // virama: 0x0DCA, + // basePos: 'Last_Sinhala', + // rephPos: POSITIONS.After_Main, + // rephMode: 'Explicit', + // blwfMode: 'Pre_And_Post' + // }, + + Khmer: { + hasOldSpec: false, + virama: 0x17D2, + basePos: 'First', + rephPos: POSITIONS.Ra_To_Become_Reph, + rephMode: 'Vis_Repha', + blwfMode: 'Pre_And_Post' + } +}; + +// Additional decompositions that aren't in Unicode +export const INDIC_DECOMPOSITIONS = { + // Khmer + 0x17BE: [0x17C1, 0x17BE], + 0x17BF: [0x17C1, 0x17BF], + 0x17C0: [0x17C1, 0x17C0], + 0x17C4: [0x17C1, 0x17C4], + 0x17C5: [0x17C1, 0x17C5] +}; diff --git a/node_modules/fontkit/src/opentype/shapers/indic.json b/node_modules/fontkit/src/opentype/shapers/indic.json new file mode 100644 index 0000000000000000000000000000000000000000..dd3a3f9cb9e143ecdfbb3d2a2568fccf98f4d8e2 --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/indic.json @@ -0,0 +1 @@ +{"stateTable":[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,2,3,4,5,6,7,8,9,0,10,11,11,12,13,14,15,16,17],[0,0,0,18,19,20,21,22,23,0,24,0,0,25,26,0,0,27,0],[0,0,0,28,29,30,31,32,33,0,34,0,0,35,36,0,0,37,0],[0,0,0,38,5,7,7,8,9,0,10,0,0,0,13,0,0,16,0],[0,39,0,0,0,40,41,0,9,0,10,0,0,0,42,0,39,0,0],[0,0,0,0,43,44,44,8,9,0,0,0,0,12,43,0,0,0,0],[0,0,0,0,43,44,44,8,9,0,0,0,0,0,43,0,0,0,0],[0,0,0,45,46,47,48,49,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,50,0,0,51,0,10,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,52,0,0,0,0,0,0,0,0],[0,0,0,53,54,55,56,57,58,0,59,0,0,60,61,0,0,62,0],[0,0,0,4,5,7,7,8,9,0,10,0,0,0,13,0,0,16,0],[0,63,64,0,0,40,41,0,9,0,10,0,0,0,42,0,63,0,0],[0,2,3,4,5,6,7,8,9,0,10,11,11,12,13,0,2,16,0],[0,0,0,18,65,20,21,22,23,0,24,0,0,25,26,0,0,27,0],[0,0,0,0,66,67,67,8,9,0,10,0,0,0,68,0,0,0,0],[0,0,0,69,0,70,70,0,71,0,72,0,0,0,0,0,0,0,0],[0,0,0,73,19,74,74,22,23,0,24,0,0,0,26,0,0,27,0],[0,75,0,0,0,76,77,0,23,0,24,0,0,0,78,0,75,0,0],[0,0,0,0,79,80,80,22,23,0,0,0,0,25,79,0,0,0,0],[0,0,0,18,19,20,74,22,23,0,24,0,0,25,26,0,0,27,0],[0,0,0,81,82,83,84,85,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,86,0,0,87,0,24,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,88,0,0,0,0,0,0,0,0],[0,0,0,18,19,74,74,22,23,0,24,0,0,0,26,0,0,27,0],[0,89,90,0,0,76,77,0,23,0,24,0,0,0,78,0,89,0,0],[0,0,0,0,91,92,92,22,23,0,24,0,0,0,93,0,0,0,0],[0,0,0,94,29,95,31,32,33,0,34,0,0,0,36,0,0,37,0],[0,96,0,0,0,97,98,0,33,0,34,0,0,0,99,0,96,0,0],[0,0,0,0,100,101,101,32,33,0,0,0,0,35,100,0,0,0,0],[0,0,0,0,100,101,101,32,33,0,0,0,0,0,100,0,0,0,0],[0,0,0,102,103,104,105,106,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,107,0,0,108,0,34,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,109,0,0,0,0,0,0,0,0],[0,0,0,28,29,95,31,32,33,0,34,0,0,0,36,0,0,37,0],[0,110,111,0,0,97,98,0,33,0,34,0,0,0,99,0,110,0,0],[0,0,0,0,112,113,113,32,33,0,34,0,0,0,114,0,0,0,0],[0,0,0,0,5,7,7,8,9,0,10,0,0,0,13,0,0,16,0],[0,0,0,115,116,117,118,8,9,0,10,0,0,119,120,0,0,16,0],[0,0,0,0,0,121,121,0,9,0,10,0,0,0,42,0,0,0,0],[0,39,0,122,0,123,123,8,9,0,10,0,0,0,42,0,39,0,0],[0,124,64,0,0,0,0,0,0,0,0,0,0,0,0,0,124,0,0],[0,39,0,0,0,121,125,0,9,0,10,0,0,0,42,0,39,0,0],[0,0,0,0,0,126,126,8,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,46,47,48,49,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,47,47,49,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,127,127,49,9,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,128,127,127,49,9,0,0,0,0,0,0,0,0,0,0],[0,0,0,129,130,131,132,133,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0],[0,0,0,0,0,50,0,0,0,0,10,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,134,0,0,0,0,0,0,0,0],[0,0,0,135,54,56,56,57,58,0,59,0,0,0,61,0,0,62,0],[0,136,0,0,0,137,138,0,58,0,59,0,0,0,139,0,136,0,0],[0,0,0,0,140,141,141,57,58,0,0,0,0,60,140,0,0,0,0],[0,0,0,0,140,141,141,57,58,0,0,0,0,0,140,0,0,0,0],[0,0,0,142,143,144,145,146,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,147,0,0,148,0,59,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,149,0,0,0,0,0,0,0,0],[0,0,0,53,54,56,56,57,58,0,59,0,0,0,61,0,0,62,0],[0,150,151,0,0,137,138,0,58,0,59,0,0,0,139,0,150,0,0],[0,0,0,0,152,153,153,57,58,0,59,0,0,0,154,0,0,0,0],[0,0,0,155,116,156,157,8,9,0,10,0,0,158,120,0,0,16,0],[0,0,0,0,0,121,121,0,9,0,10,0,0,0,0,0,0,0,0],[0,75,3,4,5,159,160,8,161,0,162,0,11,12,163,0,75,16,0],[0,0,0,0,0,40,164,0,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,165,44,44,8,9,0,0,0,0,0,165,0,0,0,0],[0,124,64,0,0,40,164,0,9,0,10,0,0,0,42,0,124,0,0],[0,0,0,0,0,70,70,0,71,0,72,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,71,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,166,0,0,167,0,72,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,168,0,0,0,0,0,0,0,0],[0,0,0,0,19,74,74,22,23,0,24,0,0,0,26,0,0,27,0],[0,0,0,0,79,80,80,22,23,0,0,0,0,0,79,0,0,0,0],[0,0,0,169,170,171,172,22,23,0,24,0,0,173,174,0,0,27,0],[0,0,0,0,0,175,175,0,23,0,24,0,0,0,78,0,0,0,0],[0,75,0,176,0,177,177,22,23,0,24,0,0,0,78,0,75,0,0],[0,178,90,0,0,0,0,0,0,0,0,0,0,0,0,0,178,0,0],[0,75,0,0,0,175,179,0,23,0,24,0,0,0,78,0,75,0,0],[0,0,0,0,0,180,180,22,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,82,83,84,85,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,83,83,85,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,181,181,85,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,182,181,181,85,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,183,184,185,186,187,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,0],[0,0,0,0,0,86,0,0,0,0,24,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,188,0,0,0,0,0,0,0,0],[0,0,0,189,170,190,191,22,23,0,24,0,0,192,174,0,0,27,0],[0,0,0,0,0,175,175,0,23,0,24,0,0,0,0,0,0,0,0],[0,0,0,0,0,76,193,0,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,194,80,80,22,23,0,0,0,0,0,194,0,0,0,0],[0,178,90,0,0,76,193,0,23,0,24,0,0,0,78,0,178,0,0],[0,0,0,0,29,95,31,32,33,0,34,0,0,0,36,0,0,37,0],[0,0,0,0,100,101,101,32,33,0,0,0,0,0,100,0,0,0,0],[0,0,0,195,196,197,198,32,33,0,34,0,0,199,200,0,0,37,0],[0,0,0,0,0,201,201,0,33,0,34,0,0,0,99,0,0,0,0],[0,96,0,202,0,203,203,32,33,0,34,0,0,0,99,0,96,0,0],[0,204,111,0,0,0,0,0,0,0,0,0,0,0,0,0,204,0,0],[0,96,0,0,0,201,205,0,33,0,34,0,0,0,99,0,96,0,0],[0,0,0,0,0,206,206,32,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,103,104,105,106,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,104,104,106,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,207,207,106,33,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,208,207,207,106,33,0,0,0,0,0,0,0,0,0,0],[0,0,0,209,210,211,212,213,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,34,0,0,0,0,0,0,0,0],[0,0,0,0,0,107,0,0,0,0,34,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,214,0,0,0,0,0,0,0,0],[0,0,0,215,196,216,217,32,33,0,34,0,0,218,200,0,0,37,0],[0,0,0,0,0,201,201,0,33,0,34,0,0,0,0,0,0,0,0],[0,0,0,0,0,97,219,0,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,220,101,101,32,33,0,0,0,0,0,220,0,0,0,0],[0,204,111,0,0,97,219,0,33,0,34,0,0,0,99,0,204,0,0],[0,0,0,221,116,222,222,8,9,0,10,0,0,0,120,0,0,16,0],[0,223,0,0,0,40,224,0,9,0,10,0,0,0,42,0,223,0,0],[0,0,0,0,225,44,44,8,9,0,0,0,0,119,225,0,0,0,0],[0,0,0,115,116,117,222,8,9,0,10,0,0,119,120,0,0,16,0],[0,0,0,115,116,222,222,8,9,0,10,0,0,0,120,0,0,16,0],[0,226,64,0,0,40,224,0,9,0,10,0,0,0,42,0,226,0,0],[0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0],[0,39,0,0,0,121,121,0,9,0,10,0,0,0,42,0,39,0,0],[0,0,0,0,0,44,44,8,9,0,0,0,0,0,0,0,0,0,0],[0,0,0,227,0,228,229,0,9,0,10,0,0,230,0,0,0,0,0],[0,39,0,122,0,121,121,0,9,0,10,0,0,0,42,0,39,0,0],[0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,231,231,49,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,232,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,130,131,132,133,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,131,131,133,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,233,233,133,9,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,234,233,233,133,9,0,0,0,0,0,0,0,0,0,0],[0,0,0,235,236,237,238,239,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,54,56,56,57,58,0,59,0,0,0,61,0,0,62,0],[0,0,0,240,241,242,243,57,58,0,59,0,0,244,245,0,0,62,0],[0,0,0,0,0,246,246,0,58,0,59,0,0,0,139,0,0,0,0],[0,136,0,247,0,248,248,57,58,0,59,0,0,0,139,0,136,0,0],[0,249,151,0,0,0,0,0,0,0,0,0,0,0,0,0,249,0,0],[0,136,0,0,0,246,250,0,58,0,59,0,0,0,139,0,136,0,0],[0,0,0,0,0,251,251,57,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,143,144,145,146,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,144,144,146,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,252,252,146,58,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,253,252,252,146,58,0,0,0,0,0,0,0,0,0,0],[0,0,0,254,255,256,257,258,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,59,0,0,0,0,0,0,0,0],[0,0,0,0,0,147,0,0,0,0,59,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,259,0,0,0,0,0,0,0,0],[0,0,0,260,241,261,262,57,58,0,59,0,0,263,245,0,0,62,0],[0,0,0,0,0,246,246,0,58,0,59,0,0,0,0,0,0,0,0],[0,0,0,0,0,137,264,0,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,265,141,141,57,58,0,0,0,0,0,265,0,0,0,0],[0,249,151,0,0,137,264,0,58,0,59,0,0,0,139,0,249,0,0],[0,0,0,221,116,222,222,8,9,0,10,0,0,0,120,0,0,16,0],[0,0,0,0,225,44,44,8,9,0,0,0,0,158,225,0,0,0,0],[0,0,0,155,116,156,222,8,9,0,10,0,0,158,120,0,0,16,0],[0,0,0,155,116,222,222,8,9,0,10,0,0,0,120,0,0,16,0],[0,0,0,0,43,266,266,8,161,0,24,0,0,12,267,0,0,0,0],[0,75,0,176,43,268,268,269,161,0,24,0,0,0,267,0,75,0,0],[0,0,0,0,0,270,0,0,271,0,162,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,272,0,0,0,0,0,0,0,0],[0,273,274,0,0,40,41,0,9,0,10,0,0,0,42,0,273,0,0],[0,0,0,40,0,123,123,8,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,121,275,0,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,72,0,0,0,0,0,0,0,0],[0,0,0,0,0,166,0,0,0,0,72,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,276,0,0,0,0,0,0,0,0],[0,0,0,277,170,278,278,22,23,0,24,0,0,0,174,0,0,27,0],[0,279,0,0,0,76,280,0,23,0,24,0,0,0,78,0,279,0,0],[0,0,0,0,281,80,80,22,23,0,0,0,0,173,281,0,0,0,0],[0,0,0,169,170,171,278,22,23,0,24,0,0,173,174,0,0,27,0],[0,0,0,169,170,278,278,22,23,0,24,0,0,0,174,0,0,27,0],[0,282,90,0,0,76,280,0,23,0,24,0,0,0,78,0,282,0,0],[0,0,0,0,0,0,0,0,23,0,0,0,0,0,0,0,0,0,0],[0,75,0,0,0,175,175,0,23,0,24,0,0,0,78,0,75,0,0],[0,0,0,0,0,80,80,22,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,283,0,284,285,0,23,0,24,0,0,286,0,0,0,0,0],[0,75,0,176,0,175,175,0,23,0,24,0,0,0,78,0,75,0,0],[0,0,0,0,0,0,0,22,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,287,287,85,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,288,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,184,185,186,187,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,185,185,187,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,289,289,187,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,290,289,289,187,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,291,292,293,294,295,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,277,170,278,278,22,23,0,24,0,0,0,174,0,0,27,0],[0,0,0,0,281,80,80,22,23,0,0,0,0,192,281,0,0,0,0],[0,0,0,189,170,190,278,22,23,0,24,0,0,192,174,0,0,27,0],[0,0,0,189,170,278,278,22,23,0,24,0,0,0,174,0,0,27,0],[0,0,0,76,0,177,177,22,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,175,296,0,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,297,196,298,298,32,33,0,34,0,0,0,200,0,0,37,0],[0,299,0,0,0,97,300,0,33,0,34,0,0,0,99,0,299,0,0],[0,0,0,0,301,101,101,32,33,0,0,0,0,199,301,0,0,0,0],[0,0,0,195,196,197,298,32,33,0,34,0,0,199,200,0,0,37,0],[0,0,0,195,196,298,298,32,33,0,34,0,0,0,200,0,0,37,0],[0,302,111,0,0,97,300,0,33,0,34,0,0,0,99,0,302,0,0],[0,0,0,0,0,0,0,0,33,0,0,0,0,0,0,0,0,0,0],[0,96,0,0,0,201,201,0,33,0,34,0,0,0,99,0,96,0,0],[0,0,0,0,0,101,101,32,33,0,0,0,0,0,0,0,0,0,0],[0,0,0,303,0,304,305,0,33,0,34,0,0,306,0,0,0,0,0],[0,96,0,202,0,201,201,0,33,0,34,0,0,0,99,0,96,0,0],[0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,307,307,106,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,308,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,210,211,212,213,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,211,211,213,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,309,309,213,33,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,310,309,309,213,33,0,0,0,0,0,0,0,0,0,0],[0,0,0,311,312,313,314,315,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,297,196,298,298,32,33,0,34,0,0,0,200,0,0,37,0],[0,0,0,0,301,101,101,32,33,0,0,0,0,218,301,0,0,0,0],[0,0,0,215,196,216,298,32,33,0,34,0,0,218,200,0,0,37,0],[0,0,0,215,196,298,298,32,33,0,34,0,0,0,200,0,0,37,0],[0,0,0,97,0,203,203,32,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,201,316,0,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,116,222,222,8,9,0,10,0,0,0,120,0,0,16,0],[0,0,0,0,225,44,44,8,9,0,0,0,0,0,225,0,0,0,0],[0,0,0,317,318,319,320,8,9,0,10,0,0,321,322,0,0,16,0],[0,223,0,323,0,123,123,8,9,0,10,0,0,0,42,0,223,0,0],[0,223,0,0,0,121,324,0,9,0,10,0,0,0,42,0,223,0,0],[0,0,0,325,318,326,327,8,9,0,10,0,0,328,322,0,0,16,0],[0,0,0,64,0,121,121,0,9,0,10,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,9,0,0,0,0,230,0,0,0,0,0],[0,0,0,227,0,228,121,0,9,0,10,0,0,230,0,0,0,0,0],[0,0,0,227,0,121,121,0,9,0,10,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,49,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,46,0,0],[0,0,0,0,0,329,329,133,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,330,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,236,237,238,239,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,237,237,239,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,331,331,239,9,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,332,331,331,239,9,0,0,0,0,0,0,0,0,0,0],[0,0,0,333,40,121,334,0,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,335,241,336,336,57,58,0,59,0,0,0,245,0,0,62,0],[0,337,0,0,0,137,338,0,58,0,59,0,0,0,139,0,337,0,0],[0,0,0,0,339,141,141,57,58,0,0,0,0,244,339,0,0,0,0],[0,0,0,240,241,242,336,57,58,0,59,0,0,244,245,0,0,62,0],[0,0,0,240,241,336,336,57,58,0,59,0,0,0,245,0,0,62,0],[0,340,151,0,0,137,338,0,58,0,59,0,0,0,139,0,340,0,0],[0,0,0,0,0,0,0,0,58,0,0,0,0,0,0,0,0,0,0],[0,136,0,0,0,246,246,0,58,0,59,0,0,0,139,0,136,0,0],[0,0,0,0,0,141,141,57,58,0,0,0,0,0,0,0,0,0,0],[0,0,0,341,0,342,343,0,58,0,59,0,0,344,0,0,0,0,0],[0,136,0,247,0,246,246,0,58,0,59,0,0,0,139,0,136,0,0],[0,0,0,0,0,0,0,57,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,345,345,146,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,346,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,255,256,257,258,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,256,256,258,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,347,347,258,58,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,348,347,347,258,58,0,0,0,0,0,0,0,0,0,0],[0,0,0,349,350,351,352,353,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,335,241,336,336,57,58,0,59,0,0,0,245,0,0,62,0],[0,0,0,0,339,141,141,57,58,0,0,0,0,263,339,0,0,0,0],[0,0,0,260,241,261,336,57,58,0,59,0,0,263,245,0,0,62,0],[0,0,0,260,241,336,336,57,58,0,59,0,0,0,245,0,0,62,0],[0,0,0,137,0,248,248,57,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,246,354,0,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,126,126,8,23,0,0,0,0,0,0,0,0,0,0],[0,355,90,0,0,121,125,0,9,0,10,0,0,0,42,0,355,0,0],[0,0,0,0,0,356,356,269,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,357,358,359,360,361,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,162,0,0,0,0,0,0,0,0],[0,0,0,0,0,270,0,0,0,0,162,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,363,0,0,0,0,0,0,0,0],[0,0,0,364,116,365,366,8,161,0,162,0,0,367,120,0,0,16,0],[0,0,0,0,0,368,368,0,161,0,162,0,0,0,0,0,0,0,0],[0,0,0,40,0,121,121,0,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,170,278,278,22,23,0,24,0,0,0,174,0,0,27,0],[0,0,0,0,281,80,80,22,23,0,0,0,0,0,281,0,0,0,0],[0,0,0,369,370,371,372,22,23,0,24,0,0,373,374,0,0,27,0],[0,279,0,375,0,177,177,22,23,0,24,0,0,0,78,0,279,0,0],[0,279,0,0,0,175,376,0,23,0,24,0,0,0,78,0,279,0,0],[0,0,0,377,370,378,379,22,23,0,24,0,0,380,374,0,0,27,0],[0,0,0,90,0,175,175,0,23,0,24,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,23,0,0,0,0,286,0,0,0,0,0],[0,0,0,283,0,284,175,0,23,0,24,0,0,286,0,0,0,0,0],[0,0,0,283,0,175,175,0,23,0,24,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,85,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,82,0,0],[0,0,0,0,0,381,381,187,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,382,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,292,293,294,295,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,293,293,295,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,0,383,383,295,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,384,383,383,295,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,385,76,175,386,0,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,76,0,175,175,0,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,196,298,298,32,33,0,34,0,0,0,200,0,0,37,0],[0,0,0,0,301,101,101,32,33,0,0,0,0,0,301,0,0,0,0],[0,0,0,387,388,389,390,32,33,0,34,0,0,391,392,0,0,37,0],[0,299,0,393,0,203,203,32,33,0,34,0,0,0,99,0,299,0,0],[0,299,0,0,0,201,394,0,33,0,34,0,0,0,99,0,299,0,0],[0,0,0,395,388,396,397,32,33,0,34,0,0,398,392,0,0,37,0],[0,0,0,111,0,201,201,0,33,0,34,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,33,0,0,0,0,306,0,0,0,0,0],[0,0,0,303,0,304,201,0,33,0,34,0,0,306,0,0,0,0,0],[0,0,0,303,0,201,201,0,33,0,34,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,106,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,103,0,0],[0,0,0,0,0,399,399,213,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,400,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,312,313,314,315,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,313,313,315,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,0,401,401,315,33,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,402,401,401,315,33,0,0,0,0,0,0,0,0,0,0],[0,0,0,403,97,201,404,0,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,97,0,201,201,0,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,405,318,406,406,8,9,0,10,0,0,0,322,0,0,16,0],[0,407,0,0,0,40,408,0,9,0,10,0,0,0,42,0,407,0,0],[0,0,0,0,409,44,44,8,9,0,0,0,0,321,409,0,0,0,0],[0,0,0,317,318,319,406,8,9,0,10,0,0,321,322,0,0,16,0],[0,0,0,317,318,406,406,8,9,0,10,0,0,0,322,0,0,16,0],[0,410,64,0,0,40,408,0,9,0,10,0,0,0,42,0,410,0,0],[0,223,0,0,0,121,121,0,9,0,10,0,0,0,42,0,223,0,0],[0,223,0,323,0,121,121,0,9,0,10,0,0,0,42,0,223,0,0],[0,0,0,405,318,406,406,8,9,0,10,0,0,0,322,0,0,16,0],[0,0,0,0,409,44,44,8,9,0,0,0,0,328,409,0,0,0,0],[0,0,0,325,318,326,406,8,9,0,10,0,0,328,322,0,0,16,0],[0,0,0,325,318,406,406,8,9,0,10,0,0,0,322,0,0,16,0],[0,0,0,0,0,0,0,133,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,130,0,0],[0,0,0,0,0,411,411,239,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,412,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,40,121,334,0,9,0,10,0,0,0,42,0,0,0,0],[0,0,0,0,413,0,0,0,9,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,241,336,336,57,58,0,59,0,0,0,245,0,0,62,0],[0,0,0,0,339,141,141,57,58,0,0,0,0,0,339,0,0,0,0],[0,0,0,414,415,416,417,57,58,0,59,0,0,418,419,0,0,62,0],[0,337,0,420,0,248,248,57,58,0,59,0,0,0,139,0,337,0,0],[0,337,0,0,0,246,421,0,58,0,59,0,0,0,139,0,337,0,0],[0,0,0,422,415,423,424,57,58,0,59,0,0,425,419,0,0,62,0],[0,0,0,151,0,246,246,0,58,0,59,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,58,0,0,0,0,344,0,0,0,0,0],[0,0,0,341,0,342,246,0,58,0,59,0,0,344,0,0,0,0,0],[0,0,0,341,0,246,246,0,58,0,59,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,146,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,143,0,0],[0,0,0,0,0,426,426,258,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,427,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,350,351,352,353,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,351,351,353,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,0,428,428,353,58,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,429,428,428,353,58,0,0,0,0,0,0,0,0,0,0],[0,0,0,430,137,246,431,0,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,137,0,246,246,0,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,432,116,433,434,8,161,0,162,0,0,435,120,0,0,16,0],[0,0,0,0,0,180,180,269,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,358,359,360,361,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,0,359,359,361,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,0,436,436,361,161,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,437,436,436,361,161,0,0,0,0,0,0,0,0,0,0],[0,0,0,438,439,440,441,442,161,0,162,0,0,0,362,0,0,0,0],[0,443,274,0,0,0,0,0,0,0,0,0,0,0,0,0,443,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,444,116,445,445,8,161,0,162,0,0,0,120,0,0,16,0],[0,0,0,0,225,44,44,8,161,0,0,0,0,367,225,0,0,0,0],[0,0,0,364,116,365,445,8,161,0,162,0,0,367,120,0,0,16,0],[0,0,0,364,116,445,445,8,161,0,162,0,0,0,120,0,0,16,0],[0,0,0,0,0,0,0,0,161,0,0,0,0,0,0,0,0,0,0],[0,0,0,446,370,447,447,22,23,0,24,0,0,0,374,0,0,27,0],[0,448,0,0,0,76,449,0,23,0,24,0,0,0,78,0,448,0,0],[0,0,0,0,450,80,80,22,23,0,0,0,0,373,450,0,0,0,0],[0,0,0,369,370,371,447,22,23,0,24,0,0,373,374,0,0,27,0],[0,0,0,369,370,447,447,22,23,0,24,0,0,0,374,0,0,27,0],[0,451,90,0,0,76,449,0,23,0,24,0,0,0,78,0,451,0,0],[0,279,0,0,0,175,175,0,23,0,24,0,0,0,78,0,279,0,0],[0,279,0,375,0,175,175,0,23,0,24,0,0,0,78,0,279,0,0],[0,0,0,446,370,447,447,22,23,0,24,0,0,0,374,0,0,27,0],[0,0,0,0,450,80,80,22,23,0,0,0,0,380,450,0,0,0,0],[0,0,0,377,370,378,447,22,23,0,24,0,0,380,374,0,0,27,0],[0,0,0,377,370,447,447,22,23,0,24,0,0,0,374,0,0,27,0],[0,0,0,0,0,0,0,187,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,184,0,0],[0,0,0,0,0,452,452,295,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,453,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,76,175,386,0,23,0,24,0,0,0,78,0,0,0,0],[0,0,0,0,454,0,0,0,23,0,0,0,0,0,0,0,0,0,0],[0,0,0,455,388,456,456,32,33,0,34,0,0,0,392,0,0,37,0],[0,457,0,0,0,97,458,0,33,0,34,0,0,0,99,0,457,0,0],[0,0,0,0,459,101,101,32,33,0,0,0,0,391,459,0,0,0,0],[0,0,0,387,388,389,456,32,33,0,34,0,0,391,392,0,0,37,0],[0,0,0,387,388,456,456,32,33,0,34,0,0,0,392,0,0,37,0],[0,460,111,0,0,97,458,0,33,0,34,0,0,0,99,0,460,0,0],[0,299,0,0,0,201,201,0,33,0,34,0,0,0,99,0,299,0,0],[0,299,0,393,0,201,201,0,33,0,34,0,0,0,99,0,299,0,0],[0,0,0,455,388,456,456,32,33,0,34,0,0,0,392,0,0,37,0],[0,0,0,0,459,101,101,32,33,0,0,0,0,398,459,0,0,0,0],[0,0,0,395,388,396,456,32,33,0,34,0,0,398,392,0,0,37,0],[0,0,0,395,388,456,456,32,33,0,34,0,0,0,392,0,0,37,0],[0,0,0,0,0,0,0,213,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,210,0,0],[0,0,0,0,0,461,461,315,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,462,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,97,201,404,0,33,0,34,0,0,0,99,0,0,0,0],[0,0,0,0,463,0,0,0,33,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,318,406,406,8,9,0,10,0,0,0,322,0,0,16,0],[0,0,0,0,409,44,44,8,9,0,0,0,0,0,409,0,0,0,0],[0,0,0,464,465,466,467,8,9,0,10,0,0,468,469,0,0,16,0],[0,407,0,470,0,123,123,8,9,0,10,0,0,0,42,0,407,0,0],[0,407,0,0,0,121,471,0,9,0,10,0,0,0,42,0,407,0,0],[0,0,0,472,465,473,474,8,9,0,10,0,0,475,469,0,0,16,0],[0,0,0,0,0,0,0,239,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,236,0,0],[0,0,0,0,0,0,476,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,477,415,478,478,57,58,0,59,0,0,0,419,0,0,62,0],[0,479,0,0,0,137,480,0,58,0,59,0,0,0,139,0,479,0,0],[0,0,0,0,481,141,141,57,58,0,0,0,0,418,481,0,0,0,0],[0,0,0,414,415,416,478,57,58,0,59,0,0,418,419,0,0,62,0],[0,0,0,414,415,478,478,57,58,0,59,0,0,0,419,0,0,62,0],[0,482,151,0,0,137,480,0,58,0,59,0,0,0,139,0,482,0,0],[0,337,0,0,0,246,246,0,58,0,59,0,0,0,139,0,337,0,0],[0,337,0,420,0,246,246,0,58,0,59,0,0,0,139,0,337,0,0],[0,0,0,477,415,478,478,57,58,0,59,0,0,0,419,0,0,62,0],[0,0,0,0,481,141,141,57,58,0,0,0,0,425,481,0,0,0,0],[0,0,0,422,415,423,478,57,58,0,59,0,0,425,419,0,0,62,0],[0,0,0,422,415,478,478,57,58,0,59,0,0,0,419,0,0,62,0],[0,0,0,0,0,0,0,258,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0],[0,0,0,0,0,483,483,353,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,484,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,137,246,431,0,58,0,59,0,0,0,139,0,0,0,0],[0,0,0,0,485,0,0,0,58,0,0,0,0,0,0,0,0,0,0],[0,0,0,444,116,445,445,8,161,0,162,0,0,0,120,0,0,16,0],[0,0,0,0,225,44,44,8,161,0,0,0,0,435,225,0,0,0,0],[0,0,0,432,116,433,445,8,161,0,162,0,0,435,120,0,0,16,0],[0,0,0,432,116,445,445,8,161,0,162,0,0,0,120,0,0,16,0],[0,0,0,0,0,486,486,361,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,487,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,439,440,441,442,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,0,440,440,442,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,0,488,488,442,161,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,489,488,488,442,161,0,0,0,0,0,0,0,0,0,0],[0,0,0,490,491,492,493,494,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,495,0,496,497,0,161,0,162,0,0,498,0,0,0,0,0],[0,0,0,0,116,445,445,8,161,0,162,0,0,0,120,0,0,16,0],[0,0,0,0,225,44,44,8,161,0,0,0,0,0,225,0,0,0,0],[0,0,0,0,370,447,447,22,23,0,24,0,0,0,374,0,0,27,0],[0,0,0,0,450,80,80,22,23,0,0,0,0,0,450,0,0,0,0],[0,0,0,499,500,501,502,22,23,0,24,0,0,503,504,0,0,27,0],[0,448,0,505,0,177,177,22,23,0,24,0,0,0,78,0,448,0,0],[0,448,0,0,0,175,506,0,23,0,24,0,0,0,78,0,448,0,0],[0,0,0,507,500,508,509,22,23,0,24,0,0,510,504,0,0,27,0],[0,0,0,0,0,0,0,295,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,292,0,0],[0,0,0,0,0,0,511,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,388,456,456,32,33,0,34,0,0,0,392,0,0,37,0],[0,0,0,0,459,101,101,32,33,0,0,0,0,0,459,0,0,0,0],[0,0,0,512,513,514,515,32,33,0,34,0,0,516,517,0,0,37,0],[0,457,0,518,0,203,203,32,33,0,34,0,0,0,99,0,457,0,0],[0,457,0,0,0,201,519,0,33,0,34,0,0,0,99,0,457,0,0],[0,0,0,520,513,521,522,32,33,0,34,0,0,523,517,0,0,37,0],[0,0,0,0,0,0,0,315,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,312,0,0],[0,0,0,0,0,0,524,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,525,465,526,526,8,9,0,10,0,0,0,469,0,0,16,0],[0,527,0,0,0,40,528,0,9,0,10,0,0,0,42,0,527,0,0],[0,0,0,0,529,44,44,8,9,0,0,0,0,468,529,0,0,0,0],[0,0,0,464,465,466,526,8,9,0,10,0,0,468,469,0,0,16,0],[0,0,0,464,465,526,526,8,9,0,10,0,0,0,469,0,0,16,0],[0,530,64,0,0,40,528,0,9,0,10,0,0,0,42,0,530,0,0],[0,407,0,0,0,121,121,0,9,0,10,0,0,0,42,0,407,0,0],[0,407,0,470,0,121,121,0,9,0,10,0,0,0,42,0,407,0,0],[0,0,0,525,465,526,526,8,9,0,10,0,0,0,469,0,0,16,0],[0,0,0,0,529,44,44,8,9,0,0,0,0,475,529,0,0,0,0],[0,0,0,472,465,473,526,8,9,0,10,0,0,475,469,0,0,16,0],[0,0,0,472,465,526,526,8,9,0,10,0,0,0,469,0,0,16,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,40,0,0],[0,0,0,0,415,478,478,57,58,0,59,0,0,0,419,0,0,62,0],[0,0,0,0,481,141,141,57,58,0,0,0,0,0,481,0,0,0,0],[0,0,0,531,532,533,534,57,58,0,59,0,0,535,536,0,0,62,0],[0,479,0,537,0,248,248,57,58,0,59,0,0,0,139,0,479,0,0],[0,479,0,0,0,246,538,0,58,0,59,0,0,0,139,0,479,0,0],[0,0,0,539,532,540,541,57,58,0,59,0,0,542,536,0,0,62,0],[0,0,0,0,0,0,0,353,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,350,0,0],[0,0,0,0,0,0,543,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,361,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,358,0,0],[0,0,0,0,0,544,544,442,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,545,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,491,492,493,494,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,0,492,492,494,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,0,546,546,494,161,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,547,546,546,494,161,0,0,0,0,0,0,0,0,0,0],[0,0,0,548,549,368,550,0,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,274,0,368,368,0,161,0,162,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,161,0,0,0,0,498,0,0,0,0,0],[0,0,0,495,0,496,368,0,161,0,162,0,0,498,0,0,0,0,0],[0,0,0,495,0,368,368,0,161,0,162,0,0,0,0,0,0,0,0],[0,0,0,551,500,552,552,22,23,0,24,0,0,0,504,0,0,27,0],[0,553,0,0,0,76,554,0,23,0,24,0,0,0,78,0,553,0,0],[0,0,0,0,555,80,80,22,23,0,0,0,0,503,555,0,0,0,0],[0,0,0,499,500,501,552,22,23,0,24,0,0,503,504,0,0,27,0],[0,0,0,499,500,552,552,22,23,0,24,0,0,0,504,0,0,27,0],[0,556,90,0,0,76,554,0,23,0,24,0,0,0,78,0,556,0,0],[0,448,0,0,0,175,175,0,23,0,24,0,0,0,78,0,448,0,0],[0,448,0,505,0,175,175,0,23,0,24,0,0,0,78,0,448,0,0],[0,0,0,551,500,552,552,22,23,0,24,0,0,0,504,0,0,27,0],[0,0,0,0,555,80,80,22,23,0,0,0,0,510,555,0,0,0,0],[0,0,0,507,500,508,552,22,23,0,24,0,0,510,504,0,0,27,0],[0,0,0,507,500,552,552,22,23,0,24,0,0,0,504,0,0,27,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,76,0,0],[0,0,0,557,513,558,558,32,33,0,34,0,0,0,517,0,0,37,0],[0,559,0,0,0,97,560,0,33,0,34,0,0,0,99,0,559,0,0],[0,0,0,0,561,101,101,32,33,0,0,0,0,516,561,0,0,0,0],[0,0,0,512,513,514,558,32,33,0,34,0,0,516,517,0,0,37,0],[0,0,0,512,513,558,558,32,33,0,34,0,0,0,517,0,0,37,0],[0,562,111,0,0,97,560,0,33,0,34,0,0,0,99,0,562,0,0],[0,457,0,0,0,201,201,0,33,0,34,0,0,0,99,0,457,0,0],[0,457,0,518,0,201,201,0,33,0,34,0,0,0,99,0,457,0,0],[0,0,0,557,513,558,558,32,33,0,34,0,0,0,517,0,0,37,0],[0,0,0,0,561,101,101,32,33,0,0,0,0,523,561,0,0,0,0],[0,0,0,520,513,521,558,32,33,0,34,0,0,523,517,0,0,37,0],[0,0,0,520,513,558,558,32,33,0,34,0,0,0,517,0,0,37,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,97,0,0],[0,0,0,0,465,526,526,8,9,0,10,0,0,0,469,0,0,16,0],[0,0,0,0,529,44,44,8,9,0,0,0,0,0,529,0,0,0,0],[0,0,0,563,66,564,565,8,9,0,10,0,0,566,68,0,0,16,0],[0,527,0,567,0,123,123,8,9,0,10,0,0,0,42,0,527,0,0],[0,527,0,0,0,121,568,0,9,0,10,0,0,0,42,0,527,0,0],[0,0,0,569,66,570,571,8,9,0,10,0,0,572,68,0,0,16,0],[0,0,0,573,532,574,574,57,58,0,59,0,0,0,536,0,0,62,0],[0,575,0,0,0,137,576,0,58,0,59,0,0,0,139,0,575,0,0],[0,0,0,0,577,141,141,57,58,0,0,0,0,535,577,0,0,0,0],[0,0,0,531,532,533,574,57,58,0,59,0,0,535,536,0,0,62,0],[0,0,0,531,532,574,574,57,58,0,59,0,0,0,536,0,0,62,0],[0,578,151,0,0,137,576,0,58,0,59,0,0,0,139,0,578,0,0],[0,479,0,0,0,246,246,0,58,0,59,0,0,0,139,0,479,0,0],[0,479,0,537,0,246,246,0,58,0,59,0,0,0,139,0,479,0,0],[0,0,0,573,532,574,574,57,58,0,59,0,0,0,536,0,0,62,0],[0,0,0,0,577,141,141,57,58,0,0,0,0,542,577,0,0,0,0],[0,0,0,539,532,540,574,57,58,0,59,0,0,542,536,0,0,62,0],[0,0,0,539,532,574,574,57,58,0,59,0,0,0,536,0,0,62,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,137,0,0],[0,0,0,0,0,0,0,442,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,439,0,0],[0,0,0,0,0,579,579,494,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,580,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,549,368,550,0,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,0,368,368,0,161,0,162,0,0,0,362,0,0,0,0],[0,0,0,0,581,0,0,0,161,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,500,552,552,22,23,0,24,0,0,0,504,0,0,27,0],[0,0,0,0,555,80,80,22,23,0,0,0,0,0,555,0,0,0,0],[0,0,0,582,91,583,584,22,23,0,24,0,0,585,93,0,0,27,0],[0,553,0,586,0,177,177,22,23,0,24,0,0,0,78,0,553,0,0],[0,553,0,0,0,175,587,0,23,0,24,0,0,0,78,0,553,0,0],[0,0,0,588,91,589,590,22,23,0,24,0,0,591,93,0,0,27,0],[0,0,0,0,513,558,558,32,33,0,34,0,0,0,517,0,0,37,0],[0,0,0,0,561,101,101,32,33,0,0,0,0,0,561,0,0,0,0],[0,0,0,592,112,593,594,32,33,0,34,0,0,595,114,0,0,37,0],[0,559,0,596,0,203,203,32,33,0,34,0,0,0,99,0,559,0,0],[0,559,0,0,0,201,597,0,33,0,34,0,0,0,99,0,559,0,0],[0,0,0,598,112,599,600,32,33,0,34,0,0,601,114,0,0,37,0],[0,0,0,602,66,67,67,8,9,0,10,0,0,0,68,0,0,16,0],[0,0,0,0,165,44,44,8,9,0,0,0,0,566,165,0,0,0,0],[0,0,0,563,66,564,67,8,9,0,10,0,0,566,68,0,0,16,0],[0,0,0,563,66,67,67,8,9,0,10,0,0,0,68,0,0,16,0],[0,527,0,0,0,121,121,0,9,0,10,0,0,0,42,0,527,0,0],[0,527,0,567,0,121,121,0,9,0,10,0,0,0,42,0,527,0,0],[0,0,0,602,66,67,67,8,9,0,10,0,0,0,68,0,0,16,0],[0,0,0,0,165,44,44,8,9,0,0,0,0,572,165,0,0,0,0],[0,0,0,569,66,570,67,8,9,0,10,0,0,572,68,0,0,16,0],[0,0,0,569,66,67,67,8,9,0,10,0,0,0,68,0,0,16,0],[0,0,0,0,532,574,574,57,58,0,59,0,0,0,536,0,0,62,0],[0,0,0,0,577,141,141,57,58,0,0,0,0,0,577,0,0,0,0],[0,0,0,603,152,604,605,57,58,0,59,0,0,606,154,0,0,62,0],[0,575,0,607,0,248,248,57,58,0,59,0,0,0,139,0,575,0,0],[0,575,0,0,0,246,608,0,58,0,59,0,0,0,139,0,575,0,0],[0,0,0,609,152,610,611,57,58,0,59,0,0,612,154,0,0,62,0],[0,0,0,0,0,0,0,494,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,491,0,0],[0,0,0,0,0,0,613,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,614,91,92,92,22,23,0,24,0,0,0,93,0,0,27,0],[0,0,0,0,194,80,80,22,23,0,0,0,0,585,194,0,0,0,0],[0,0,0,582,91,583,92,22,23,0,24,0,0,585,93,0,0,27,0],[0,0,0,582,91,92,92,22,23,0,24,0,0,0,93,0,0,27,0],[0,553,0,0,0,175,175,0,23,0,24,0,0,0,78,0,553,0,0],[0,553,0,586,0,175,175,0,23,0,24,0,0,0,78,0,553,0,0],[0,0,0,614,91,92,92,22,23,0,24,0,0,0,93,0,0,27,0],[0,0,0,0,194,80,80,22,23,0,0,0,0,591,194,0,0,0,0],[0,0,0,588,91,589,92,22,23,0,24,0,0,591,93,0,0,27,0],[0,0,0,588,91,92,92,22,23,0,24,0,0,0,93,0,0,27,0],[0,0,0,615,112,113,113,32,33,0,34,0,0,0,114,0,0,37,0],[0,0,0,0,220,101,101,32,33,0,0,0,0,595,220,0,0,0,0],[0,0,0,592,112,593,113,32,33,0,34,0,0,595,114,0,0,37,0],[0,0,0,592,112,113,113,32,33,0,34,0,0,0,114,0,0,37,0],[0,559,0,0,0,201,201,0,33,0,34,0,0,0,99,0,559,0,0],[0,559,0,596,0,201,201,0,33,0,34,0,0,0,99,0,559,0,0],[0,0,0,615,112,113,113,32,33,0,34,0,0,0,114,0,0,37,0],[0,0,0,0,220,101,101,32,33,0,0,0,0,601,220,0,0,0,0],[0,0,0,598,112,599,113,32,33,0,34,0,0,601,114,0,0,37,0],[0,0,0,598,112,113,113,32,33,0,34,0,0,0,114,0,0,37,0],[0,0,0,0,66,67,67,8,9,0,10,0,0,0,68,0,0,16,0],[0,0,0,616,152,153,153,57,58,0,59,0,0,0,154,0,0,62,0],[0,0,0,0,265,141,141,57,58,0,0,0,0,606,265,0,0,0,0],[0,0,0,603,152,604,153,57,58,0,59,0,0,606,154,0,0,62,0],[0,0,0,603,152,153,153,57,58,0,59,0,0,0,154,0,0,62,0],[0,575,0,0,0,246,246,0,58,0,59,0,0,0,139,0,575,0,0],[0,575,0,607,0,246,246,0,58,0,59,0,0,0,139,0,575,0,0],[0,0,0,616,152,153,153,57,58,0,59,0,0,0,154,0,0,62,0],[0,0,0,0,265,141,141,57,58,0,0,0,0,612,265,0,0,0,0],[0,0,0,609,152,610,153,57,58,0,59,0,0,612,154,0,0,62,0],[0,0,0,609,152,153,153,57,58,0,59,0,0,0,154,0,0,62,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,549,0,0],[0,0,0,0,91,92,92,22,23,0,24,0,0,0,93,0,0,27,0],[0,0,0,0,112,113,113,32,33,0,34,0,0,0,114,0,0,37,0],[0,0,0,0,152,153,153,57,58,0,59,0,0,0,154,0,0,62,0]],"accepting":[false,true,true,true,true,true,false,false,true,true,true,true,true,true,true,true,true,true,true,true,false,true,true,true,true,true,true,true,true,true,false,true,true,true,true,true,true,true,true,true,true,true,false,true,false,true,true,false,false,true,true,true,true,true,true,false,false,true,true,true,true,true,true,true,true,true,true,false,true,true,false,true,true,true,false,true,true,true,false,true,false,true,true,false,false,true,true,true,true,true,true,true,false,true,true,false,true,true,true,false,true,false,true,true,false,false,true,true,true,true,true,true,true,false,true,true,true,false,true,true,true,false,true,false,true,true,false,false,false,true,true,false,false,true,true,true,true,true,true,false,true,false,true,true,false,false,true,true,true,true,true,true,true,false,true,true,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,false,true,true,true,false,true,false,true,true,false,false,false,true,true,false,false,true,true,true,false,true,true,true,true,true,true,false,true,true,true,false,true,false,true,true,false,false,false,true,true,false,false,true,true,true,false,true,true,true,true,true,false,true,true,true,true,true,false,true,true,false,false,false,false,true,true,false,false,true,true,true,false,true,true,true,false,true,false,true,true,false,false,false,true,true,false,false,true,true,true,false,true,true,true,true,false,true,false,true,true,true,true,true,true,true,true,true,false,true,true,true,true,true,false,true,true,false,false,false,false,true,true,false,false,true,true,true,false,true,true,true,true,true,false,true,true,false,false,false,false,true,true,false,false,true,true,true,true,false,true,true,true,true,true,true,false,true,true,false,false,false,false,true,false,true,false,true,true,true,true,true,false,true,true,false,false,false,false,true,true,false,false,true,true,true,false,true,true,false,false,true,false,true,true,false,true,true,false,true,true,false,true,true,true,true,true,true,false,true,true,false,false,false,false,true,false,true,true,false,true,true,true,true,true,true,false,true,true,false,false,false,false,true,false,true,false,true,true,true,true,false,false,false,true,true,false,true,true,true,true,true,true,false,true,true,false,false,false,false,true,false,true,false,true,true,false,false,true,true,false,false,true,true,true,false,true,false,true,true,true,true,false,false,false,true,false,true,true,true,true,false,false,false,true,true,false,true,true,true,true,true,true,false,true,true,false,true,false,true,true,true,true,false,false,false,false,false,false,false,true,true,false,false,true,true,false,true,true,true,true,false,true,true,true,true,true,true,false,true,true,false,true,true,false,true,true,true,true,true,true,false,true,true,false,true,false,true,true,true,true,true,true,false,true,true,true,true,true,true,false,true,true,false,false,false,false,false,true,true,false,true,false,true,true,true,true,true,false,true,true,true,true,true,false,true,true,true,true,true,false,true,true,true,false,true,true,true,true,false,false,false,true,false,true,true,true,true,true,false,true,true,true,false,true,true,true,true,true,false,true,true,true,true,false,true,true,true,true,true,false,true,true,false,true,true,true],"tags":[[],["broken_cluster"],["consonant_syllable"],["vowel_syllable"],["broken_cluster"],["broken_cluster"],[],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["standalone_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["consonant_syllable"],["broken_cluster"],["symbol_cluster"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],[],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["standalone_cluster"],["standalone_cluster"],[],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["broken_cluster"],["broken_cluster"],["consonant_syllable","broken_cluster"],["broken_cluster"],[],["broken_cluster"],["symbol_cluster"],[],["symbol_cluster"],["symbol_cluster"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],[],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],[],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],[],[],[],["broken_cluster"],["broken_cluster"],[],[],["broken_cluster"],["broken_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],[],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["symbol_cluster"],["symbol_cluster"],["symbol_cluster"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],[],[],[],["consonant_syllable"],["consonant_syllable"],[],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],[],[],[],["vowel_syllable"],["vowel_syllable"],[],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],[],[],[],[],["broken_cluster"],["broken_cluster"],[],[],["broken_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],[],[],[],["standalone_cluster"],["standalone_cluster"],[],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["broken_cluster"],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],["broken_cluster"],["symbol_cluster"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],[],[],[],[],["consonant_syllable"],["consonant_syllable"],[],[],["consonant_syllable"],["consonant_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],[],[],[],[],["vowel_syllable"],["vowel_syllable"],[],[],["vowel_syllable"],["vowel_syllable"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],[],[],[],[],["broken_cluster"],[],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],[],[],[],[],["standalone_cluster"],["standalone_cluster"],[],[],["standalone_cluster"],["standalone_cluster"],["consonant_syllable","broken_cluster"],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],[],["consonant_syllable","broken_cluster"],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],[],[],[],[],["consonant_syllable"],[],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],[],[],[],[],["vowel_syllable"],[],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],[],[],[],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],[],[],[],[],["standalone_cluster"],[],["consonant_syllable","broken_cluster"],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],[],[],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],[],[],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],[],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],[],[],[],[],[],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],[],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],[],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],[],[],[],[],[],["consonant_syllable","broken_cluster"],["consonant_syllable","broken_cluster"],[],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],[],[],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],["consonant_syllable"],[],["consonant_syllable"],["consonant_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],["vowel_syllable"],[],["vowel_syllable"],["vowel_syllable"],["broken_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],["standalone_cluster"],[],["standalone_cluster"],["standalone_cluster"],[],["consonant_syllable"],["vowel_syllable"],["standalone_cluster"]]} \ No newline at end of file diff --git a/node_modules/fontkit/src/opentype/shapers/indic.machine b/node_modules/fontkit/src/opentype/shapers/indic.machine new file mode 100644 index 0000000000000000000000000000000000000000..9c9c6496760e0d0eaba03633b2670b19ee8eadcf --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/indic.machine @@ -0,0 +1,31 @@ +c = C | Ra; # is_consonant +n = (ZWNJ? RS)? (N N?)?; # is_consonant_modifier +z = ZWJ | ZWNJ; # is_joiner +h = H | Coeng; # is_halant_or_coeng +reph = Ra H | Repha; # possible reph + +cn = c ZWJ? n?; +forced_rakar = ZWJ H ZWJ Ra; +symbol = Symbol N?; +matra_group = z{0,3} M N? (H | forced_rakar)?; +# syllable_tail = (z? SM SM? ZWNJ?)? A{0,3} VD{0,2}; +syllable_tail = (z? SM SM? ZWNJ?)? A{0,3}; +place_holder = Placeholder | Dotted_Circle; +halant_group = z? h (ZWJ N?)?; +final_halant_group = halant_group | h ZWNJ; +medial_group = CM?; +halant_or_matra_group = (final_halant_group | (h ZWJ)? matra_group{0,4}) (Coeng (cn | V))?; + +consonant_syllable = Repha? (cn halant_group){0,4} cn medial_group halant_or_matra_group syllable_tail; +vowel_syllable = reph? V n? (ZWJ | (halant_group cn){0,4} medial_group halant_or_matra_group syllable_tail); +standalone_cluster = (Repha? Placeholder | reph? Dotted_Circle) n? (halant_group cn){0,4} medial_group halant_or_matra_group syllable_tail; +symbol_cluster = symbol syllable_tail; +broken_cluster = reph? n? (halant_group cn){0,4} medial_group halant_or_matra_group syllable_tail; + +main = + consonant_syllable:consonant_syllable + | vowel_syllable:vowel_syllable + | standalone_cluster:standalone_cluster + | symbol_cluster:symbol_cluster + | broken_cluster:broken_cluster +; diff --git a/node_modules/fontkit/src/opentype/shapers/indic.trie b/node_modules/fontkit/src/opentype/shapers/indic.trie new file mode 100644 index 0000000000000000000000000000000000000000..511b5a169135c290cd1701c99779f0256603b0c2 Binary files /dev/null and b/node_modules/fontkit/src/opentype/shapers/indic.trie differ diff --git a/node_modules/fontkit/src/opentype/shapers/use.json b/node_modules/fontkit/src/opentype/shapers/use.json new file mode 100644 index 0000000000000000000000000000000000000000..68581e1b34d770e13b0bc0c519186c4664706885 --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/use.json @@ -0,0 +1 @@ +{"categories":["O","IND","S","GB","B","FM","CGJ","VMAbv","VMPst","VAbv","VPst","CMBlw","VPre","VBlw","H","VMBlw","CMAbv","MBlw","CS","R","SUB","MPst","MPre","FAbv","FPst","FBlw","null","SMAbv","SMBlw","VMPre","ZWNJ","ZWJ","WJ","M","VS","N","HN","MAbv"],"decompositions":{"2507":[2503,2494],"2508":[2503,2519],"2888":[2887,2902],"2891":[2887,2878],"2892":[2887,2903],"3018":[3014,3006],"3019":[3015,3006],"3020":[3014,3031],"3144":[3142,3158],"3264":[3263,3285],"3271":[3270,3285],"3272":[3270,3286],"3274":[3270,3266],"3275":[3270,3266,3285],"3402":[3398,3390],"3403":[3399,3390],"3404":[3398,3415],"3546":[3545,3530],"3548":[3545,3535],"3549":[3545,3535,3530],"3550":[3545,3551],"3635":[3661,3634],"3763":[3789,3762],"3955":[3953,3954],"3957":[3953,3956],"3958":[4018,3968],"3959":[4018,3953,3968],"3960":[4019,3968],"3961":[4019,3953,3968],"3969":[3953,3968],"6971":[6970,6965],"6973":[6972,6965],"6976":[6974,6965],"6977":[6975,6965],"6979":[6978,6965],"69934":[69937,69927],"69935":[69938,69927],"70475":[70471,70462],"70476":[70471,70487],"70843":[70841,70842],"70844":[70841,70832],"70846":[70841,70845],"71098":[71096,71087],"71099":[71097,71087]},"stateTable":[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[2,2,3,4,4,5,0,6,7,8,9,10,11,12,13,14,15,16,0,17,18,11,19,20,21,22,0,0,0,23,0,0,2,0,0,24,0,25],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,26,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,27,28,0,0,0,0,0,27,0,0,0],[0,0,0,0,0,29,0,30,31,32,33,34,35,36,37,38,39,40,0,0,41,35,42,43,44,45,0,0,0,46,0,0,0,0,39,0,0,47],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,6,7,0,0,0,0,0,0,14,0,0,0,0,0,0,0,20,21,22,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,0,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,21,22,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,6,7,8,9,0,0,12,0,14,0,0,0,0,0,0,0,20,21,22,0,0,0,23,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,6,7,0,9,0,0,0,0,14,0,0,0,0,0,0,0,20,21,22,0,0,0,23,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,6,7,8,9,10,11,12,13,14,0,16,0,0,18,11,19,20,21,22,0,0,0,23,0,0,0,0,0,0,0,25],[0,0,0,0,0,5,0,6,7,8,9,0,11,12,0,14,0,0,0,0,0,0,0,20,21,22,0,0,0,23,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,6,7,0,9,0,0,12,0,14,0,0,0,0,0,0,0,20,21,22,0,0,0,23,0,0,0,0,0,0,0,0],[0,0,0,0,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,0,7,0,0,0,0,0,0,14,0,0,0,0,0,0,0,20,21,22,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,6,7,8,9,10,11,12,13,14,15,16,0,0,18,11,19,20,21,22,0,0,0,23,0,0,0,0,0,0,0,25],[0,0,0,0,0,5,0,6,7,8,9,0,11,12,0,14,0,0,0,0,0,11,0,20,21,22,0,0,0,23,0,0,0,0,0,0,0,0],[0,0,0,4,4,5,0,6,7,8,9,10,11,12,13,14,15,16,0,0,18,11,19,20,21,22,0,0,0,23,0,0,0,0,0,0,0,25],[0,0,0,0,0,5,0,6,7,8,9,48,11,12,13,14,48,16,0,0,18,11,19,20,21,22,0,0,0,23,0,0,0,0,49,0,0,25],[0,0,0,0,0,5,0,6,7,8,9,0,11,12,0,14,0,16,0,0,0,11,0,20,21,22,0,0,0,23,0,0,0,0,0,0,0,25],[0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,21,22,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,21,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,21,22,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,6,7,0,0,0,0,0,0,14,0,0,0,0,0,0,0,20,21,22,0,0,0,23,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,50,0,51,0],[0,0,0,0,0,5,0,6,7,8,9,0,11,12,0,14,0,16,0,0,0,11,0,20,21,22,0,0,0,23,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,27,28,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,28,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,0,0,0,0,0,0,38,0,0,0,0,0,0,0,43,44,45,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,0,31,0,0,0,0,0,0,0,0,0,0,0,0,0,0,43,44,45,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,32,33,0,0,36,0,38,0,0,0,0,0,0,0,43,44,45,0,0,0,46,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,0,33,0,0,0,0,38,0,0,0,0,0,0,0,43,44,45,0,0,0,46,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,32,33,34,35,36,37,38,0,40,0,0,41,35,42,43,44,45,0,0,0,46,0,0,0,0,0,0,0,47],[0,0,0,0,0,29,0,30,31,32,33,0,35,36,0,38,0,0,0,0,0,0,0,43,44,45,0,0,0,46,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,0,33,0,0,36,0,38,0,0,0,0,0,0,0,43,44,45,0,0,0,46,0,0,0,0,0,0,0,0],[0,0,0,0,41,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,0,31,0,0,0,0,0,0,38,0,0,0,0,0,0,0,43,44,45,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,32,33,34,35,36,37,38,39,40,0,0,41,35,42,43,44,45,0,0,0,46,0,0,0,0,0,0,0,47],[0,0,0,0,0,29,0,30,31,32,33,0,35,36,0,38,0,0,0,0,0,35,0,43,44,45,0,0,0,46,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,32,33,52,35,36,37,38,52,40,0,0,41,35,42,43,44,45,0,0,0,46,0,0,0,0,53,0,0,47],[0,0,0,0,0,29,0,30,31,32,33,0,35,36,0,38,0,40,0,0,0,35,0,43,44,45,0,0,0,46,0,0,0,0,0,0,0,47],[0,0,0,0,0,29,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,43,44,45,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,44,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,44,45,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,0,0,0,0,0,0,38,0,0,0,0,0,0,0,43,44,45,0,0,0,46,0,0,0,0,0,0,0,0],[0,0,0,0,0,29,0,30,31,32,33,0,35,36,0,38,0,40,0,0,0,35,0,43,44,45,0,0,0,46,0,0,0,0,0,0,0,0],[0,0,0,0,0,5,0,6,7,8,9,48,11,12,13,14,0,16,0,0,18,11,19,20,21,22,0,0,0,23,0,0,0,0,0,0,0,25],[0,0,0,0,0,5,0,6,7,8,9,48,11,12,13,14,48,16,0,0,18,11,19,20,21,22,0,0,0,23,0,0,0,0,0,0,0,25],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,51,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,54,0,0],[0,0,0,0,0,29,0,30,31,32,33,52,35,36,37,38,0,40,0,0,41,35,42,43,44,45,0,0,0,46,0,0,0,0,0,0,0,47],[0,0,0,0,0,29,0,30,31,32,33,52,35,36,37,38,52,40,0,0,41,35,42,43,44,45,0,0,0,46,0,0,0,0,0,0,0,47],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,50,0,51,0]],"accepting":[false,true,true,true,true,true,true,true,true,true,true,true,true,false,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true],"tags":[[],["broken_cluster"],["independent_cluster"],["symbol_cluster"],["standard_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],[],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["broken_cluster"],["numeral_cluster"],["broken_cluster"],["independent_cluster"],["symbol_cluster"],["symbol_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["virama_terminated_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["standard_cluster"],["broken_cluster"],["broken_cluster"],["numeral_cluster"],["number_joiner_terminated_cluster"],["standard_cluster"],["standard_cluster"],["numeral_cluster"]]} \ No newline at end of file diff --git a/node_modules/fontkit/src/opentype/shapers/use.machine b/node_modules/fontkit/src/opentype/shapers/use.machine new file mode 100644 index 0000000000000000000000000000000000000000..603001ceff2069602e2e8492f4f70ad85194ee29 --- /dev/null +++ b/node_modules/fontkit/src/opentype/shapers/use.machine @@ -0,0 +1,44 @@ +consonant_modifiers = CMAbv* CMBlw* ((H B | SUB) VS? CMAbv? CMBlw*)*; +medial_consonants = MPre? MAbv? MBlw? MPst?; +dependent_vowels = VPre* VAbv* VBlw* VPst*; +vowel_modifiers = VMPre* VMAbv* VMBlw* VMPst*; +final_consonants = FAbv* FBlw* FPst* FM?; + +virama_terminated_cluster = + R? (B | GB) VS? + consonant_modifiers + H +; + +standard_cluster = + R? (B | GB) VS? + consonant_modifiers + medial_consonants + dependent_vowels + vowel_modifiers + final_consonants +; + +broken_cluster = + R? + consonant_modifiers + medial_consonants + dependent_vowels + vowel_modifiers + final_consonants +; + +number_joiner_terminated_cluster = N VS? (HN N VS?)* HN; +numeral_cluster = N VS? (HN N VS?)*; +symbol_cluster = S VS? SMAbv* SMBlw*; +independent_cluster = (IND | O | WJ) VS?; + +main = + independent_cluster:independent_cluster + | virama_terminated_cluster:virama_terminated_cluster + | standard_cluster:standard_cluster + | number_joiner_terminated_cluster:number_joiner_terminated_cluster + | numeral_cluster:numeral_cluster + | symbol_cluster:symbol_cluster + | broken_cluster:broken_cluster +; diff --git a/node_modules/fontkit/src/opentype/shapers/use.trie b/node_modules/fontkit/src/opentype/shapers/use.trie new file mode 100644 index 0000000000000000000000000000000000000000..518e74d5f3fb82cb6bdca5535a6aa41515de482c Binary files /dev/null and b/node_modules/fontkit/src/opentype/shapers/use.trie differ diff --git a/node_modules/fontkit/src/subset/CFFSubset.js b/node_modules/fontkit/src/subset/CFFSubset.js new file mode 100644 index 0000000000000000000000000000000000000000..d4506e7b55f9c476f26f7914864a44e767dade0e --- /dev/null +++ b/node_modules/fontkit/src/subset/CFFSubset.js @@ -0,0 +1,171 @@ +import Subset from './Subset'; +import CFFTop from '../cff/CFFTop'; +import CFFPrivateDict from '../cff/CFFPrivateDict'; +import standardStrings from '../cff/CFFStandardStrings'; + +export default class CFFSubset extends Subset { + constructor(font) { + super(font); + + this.cff = this.font['CFF ']; + if (!this.cff) { + throw new Error('Not a CFF Font'); + } + } + + subsetCharstrings() { + this.charstrings = []; + let gsubrs = {}; + + for (let gid of this.glyphs) { + this.charstrings.push(this.cff.getCharString(gid)); + + let glyph = this.font.getGlyph(gid); + let path = glyph.path; // this causes the glyph to be parsed + + for (let subr in glyph._usedGsubrs) { + gsubrs[subr] = true; + } + } + + this.gsubrs = this.subsetSubrs(this.cff.globalSubrIndex, gsubrs); + } + + subsetSubrs(subrs, used) { + let res = []; + for (let i = 0; i < subrs.length; i++) { + let subr = subrs[i]; + if (used[i]) { + this.cff.stream.pos = subr.offset; + res.push(this.cff.stream.readBuffer(subr.length)); + } else { + res.push(new Uint8Array([11])); // return + } + } + + return res; + } + + subsetFontdict(topDict) { + topDict.FDArray = []; + topDict.FDSelect = { + version: 0, + fds: [] + }; + + let used_fds = {}; + let used_subrs = []; + let fd_select = {}; + for (let gid of this.glyphs) { + let fd = this.cff.fdForGlyph(gid); + if (fd == null) { + continue; + } + + if (!used_fds[fd]) { + topDict.FDArray.push(Object.assign({}, this.cff.topDict.FDArray[fd])); + used_subrs.push({}); + fd_select[fd] = topDict.FDArray.length - 1; + } + + used_fds[fd] = true; + topDict.FDSelect.fds.push(fd_select[fd]); + + let glyph = this.font.getGlyph(gid); + let path = glyph.path; // this causes the glyph to be parsed + for (let subr in glyph._usedSubrs) { + used_subrs[fd_select[fd]][subr] = true; + } + } + + for (let i = 0; i < topDict.FDArray.length; i++) { + let dict = topDict.FDArray[i]; + delete dict.FontName; + if (dict.Private && dict.Private.Subrs) { + dict.Private = Object.assign({}, dict.Private); + dict.Private.Subrs = this.subsetSubrs(dict.Private.Subrs, used_subrs[i]); + } + } + + return; + } + + createCIDFontdict(topDict) { + let used_subrs = {}; + for (let gid of this.glyphs) { + let glyph = this.font.getGlyph(gid); + let path = glyph.path; // this causes the glyph to be parsed + + for (let subr in glyph._usedSubrs) { + used_subrs[subr] = true; + } + } + + let privateDict = Object.assign({}, this.cff.topDict.Private); + if (this.cff.topDict.Private && this.cff.topDict.Private.Subrs) { + privateDict.Subrs = this.subsetSubrs(this.cff.topDict.Private.Subrs, used_subrs); + } + + topDict.FDArray = [{ Private: privateDict }]; + return topDict.FDSelect = { + version: 3, + nRanges: 1, + ranges: [{ first: 0, fd: 0 }], + sentinel: this.charstrings.length + }; + } + + addString(string) { + if (!string) { + return null; + } + + if (!this.strings) { + this.strings = []; + } + + this.strings.push(string); + return standardStrings.length + this.strings.length - 1; + } + + encode() { + this.subsetCharstrings(); + + let charset = { + version: this.charstrings.length > 255 ? 2 : 1, + ranges: [{ first: 1, nLeft: this.charstrings.length - 2 }] + }; + + let topDict = Object.assign({}, this.cff.topDict); + topDict.Private = null; + topDict.charset = charset; + topDict.Encoding = null; + topDict.CharStrings = this.charstrings; + + for (let key of ['version', 'Notice', 'Copyright', 'FullName', 'FamilyName', 'Weight', 'PostScript', 'BaseFontName', 'FontName']) { + topDict[key] = this.addString(this.cff.string(topDict[key])); + } + + topDict.ROS = [this.addString('Adobe'), this.addString('Identity'), 0]; + topDict.CIDCount = this.charstrings.length; + + if (this.cff.isCIDFont) { + this.subsetFontdict(topDict); + } else { + this.createCIDFontdict(topDict); + } + + let top = { + version: 1, + hdrSize: this.cff.hdrSize, + offSize: 4, + header: this.cff.header, + nameIndex: [this.cff.postscriptName], + topDictIndex: [topDict], + stringIndex: this.strings, + globalSubrIndex: this.gsubrs + }; + + return CFFTop.toBuffer(top); + } +} diff --git a/node_modules/fontkit/src/subset/Subset.js b/node_modules/fontkit/src/subset/Subset.js new file mode 100644 index 0000000000000000000000000000000000000000..06692b5af2440d3dd4223fea362bd35a3fae6392 --- /dev/null +++ b/node_modules/fontkit/src/subset/Subset.js @@ -0,0 +1,27 @@ +import * as r from 'restructure'; + +const resolved = Promise.resolve(); + +export default class Subset { + constructor(font) { + this.font = font; + this.glyphs = []; + this.mapping = {}; + + // always include the missing glyph + this.includeGlyph(0); + } + + includeGlyph(glyph) { + if (typeof glyph === 'object') { + glyph = glyph.id; + } + + if (this.mapping[glyph] == null) { + this.glyphs.push(glyph); + this.mapping[glyph] = this.glyphs.length - 1; + } + + return this.mapping[glyph]; + } +} diff --git a/node_modules/fontkit/src/subset/TTFSubset.js b/node_modules/fontkit/src/subset/TTFSubset.js new file mode 100644 index 0000000000000000000000000000000000000000..f13e5ce55552b7493edf3b14c5f0027b6d3ccc42 --- /dev/null +++ b/node_modules/fontkit/src/subset/TTFSubset.js @@ -0,0 +1,131 @@ +import cloneDeep from 'clone'; +import Subset from './Subset'; +import Directory from '../tables/directory'; +import Tables from '../tables'; +import TTFGlyphEncoder from '../glyph/TTFGlyphEncoder'; + +export default class TTFSubset extends Subset { + constructor(font) { + super(font); + this.glyphEncoder = new TTFGlyphEncoder; + } + + _addGlyph(gid) { + let glyph = this.font.getGlyph(gid); + let glyf = glyph._decode(); + + // get the offset to the glyph from the loca table + let curOffset = this.font.loca.offsets[gid]; + let nextOffset = this.font.loca.offsets[gid + 1]; + + let stream = this.font._getTableStream('glyf'); + stream.pos += curOffset; + + let buffer = stream.readBuffer(nextOffset - curOffset); + + // if it is a compound glyph, include its components + if (glyf && glyf.numberOfContours < 0) { + buffer = new Uint8Array(buffer); + let view = new DataView(buffer.buffer); + for (let component of glyf.components) { + gid = this.includeGlyph(component.glyphID); + view.setUint16(component.pos, gid); + } + } else if (glyf && this.font._variationProcessor) { + // If this is a TrueType variation glyph, re-encode the path + buffer = this.glyphEncoder.encodeSimple(glyph.path, glyf.instructions); + } + + this.glyf.push(buffer); + this.loca.offsets.push(this.offset); + + this.hmtx.metrics.push({ + advance: glyph.advanceWidth, + bearing: glyph._getMetrics().leftBearing + }); + + this.offset += buffer.length; + return this.glyf.length - 1; + } + + encode() { + // tables required by PDF spec: + // head, hhea, loca, maxp, cvt , prep, glyf, hmtx, fpgm + // + // additional tables required for standalone fonts: + // name, cmap, OS/2, post + + this.glyf = []; + this.offset = 0; + this.loca = { + offsets: [], + version: this.font.loca.version + }; + + this.hmtx = { + metrics: [], + bearings: [] + }; + + // include all the glyphs + // not using a for loop because we need to support adding more + // glyphs to the array as we go, and CoffeeScript caches the length. + let i = 0; + while (i < this.glyphs.length) { + this._addGlyph(this.glyphs[i++]); + } + + let maxp = cloneDeep(this.font.maxp); + maxp.numGlyphs = this.glyf.length; + + this.loca.offsets.push(this.offset); + + let head = cloneDeep(this.font.head); + head.indexToLocFormat = this.loca.version; + + let hhea = cloneDeep(this.font.hhea); + hhea.numberOfMetrics = this.hmtx.metrics.length; + + // map = [] + // for index in [0...256] + // if index < @numGlyphs + // map[index] = index + // else + // map[index] = 0 + // + // cmapTable = + // version: 0 + // length: 262 + // language: 0 + // codeMap: map + // + // cmap = + // version: 0 + // numSubtables: 1 + // tables: [ + // platformID: 1 + // encodingID: 0 + // table: cmapTable + // ] + + // TODO: subset prep, cvt, fpgm? + return Directory.toBuffer({ + tables: { + head, + hhea, + loca: this.loca, + maxp, + 'cvt ': this.font['cvt '], + prep: this.font.prep, + glyf: this.glyf, + hmtx: this.hmtx, + fpgm: this.font.fpgm + + // name: clone @font.name + // 'OS/2': clone @font['OS/2'] + // post: clone @font.post + // cmap: cmap + } + }); + } +} diff --git a/node_modules/fontkit/src/tables/BASE.js b/node_modules/fontkit/src/tables/BASE.js new file mode 100644 index 0000000000000000000000000000000000000000..bbb84cfbfc30742fb9c15d6945aac7208721dcc0 --- /dev/null +++ b/node_modules/fontkit/src/tables/BASE.js @@ -0,0 +1,78 @@ +import * as r from 'restructure'; +import {ScriptList, FeatureList, LookupList, Coverage, ClassDef, Device} from './opentype'; +import {ItemVariationStore} from './variations'; + +let BaseCoord = new r.VersionedStruct(r.uint16, { + 1: { // Design units only + coordinate: r.int16 // X or Y value, in design units + }, + + 2: { // Design units plus contour point + coordinate: r.int16, // X or Y value, in design units + referenceGlyph: r.uint16, // GlyphID of control glyph + baseCoordPoint: r.uint16 // Index of contour point on the referenceGlyph + }, + + 3: { // Design units plus Device table + coordinate: r.int16, // X or Y value, in design units + deviceTable: new r.Pointer(r.uint16, Device) // Device table for X or Y value + } +}); + +let BaseValues = new r.Struct({ + defaultIndex: r.uint16, // Index of default baseline for this script-same index in the BaseTagList + baseCoordCount: r.uint16, + baseCoords: new r.Array(new r.Pointer(r.uint16, BaseCoord), 'baseCoordCount') +}); + +let FeatMinMaxRecord = new r.Struct({ + tag: new r.String(4), // 4-byte feature identification tag-must match FeatureTag in FeatureList + minCoord: new r.Pointer(r.uint16, BaseCoord, {type: 'parent'}), // May be NULL + maxCoord: new r.Pointer(r.uint16, BaseCoord, {type: 'parent'}) // May be NULL +}); + +let MinMax = new r.Struct({ + minCoord: new r.Pointer(r.uint16, BaseCoord), // May be NULL + maxCoord: new r.Pointer(r.uint16, BaseCoord), // May be NULL + featMinMaxCount: r.uint16, // May be 0 + featMinMaxRecords: new r.Array(FeatMinMaxRecord, 'featMinMaxCount') // In alphabetical order +}); + +let BaseLangSysRecord = new r.Struct({ + tag: new r.String(4), // 4-byte language system identification tag + minMax: new r.Pointer(r.uint16, MinMax, {type: 'parent'}) +}); + +let BaseScript = new r.Struct({ + baseValues: new r.Pointer(r.uint16, BaseValues), // May be NULL + defaultMinMax: new r.Pointer(r.uint16, MinMax), // May be NULL + baseLangSysCount: r.uint16, // May be 0 + baseLangSysRecords: new r.Array(BaseLangSysRecord, 'baseLangSysCount') // in alphabetical order by BaseLangSysTag +}); + +let BaseScriptRecord = new r.Struct({ + tag: new r.String(4), // 4-byte script identification tag + script: new r.Pointer(r.uint16, BaseScript, {type: 'parent'}) +}); + +let BaseScriptList = new r.Array(BaseScriptRecord, r.uint16); + +// Array of 4-byte baseline identification tags-must be in alphabetical order +let BaseTagList = new r.Array(new r.String(4), r.uint16); + +let Axis = new r.Struct({ + baseTagList: new r.Pointer(r.uint16, BaseTagList), // May be NULL + baseScriptList: new r.Pointer(r.uint16, BaseScriptList) +}); + +export default new r.VersionedStruct(r.uint32, { + header: { + horizAxis: new r.Pointer(r.uint16, Axis), // May be NULL + vertAxis: new r.Pointer(r.uint16, Axis) // May be NULL + }, + + 0x00010000: {}, + 0x00010001: { + itemVariationStore: new r.Pointer(r.uint32, ItemVariationStore) + } +}); diff --git a/node_modules/fontkit/src/tables/COLR.js b/node_modules/fontkit/src/tables/COLR.js new file mode 100644 index 0000000000000000000000000000000000000000..6a4b1697912cf0bbab417ca356d5778d4f476a2c --- /dev/null +++ b/node_modules/fontkit/src/tables/COLR.js @@ -0,0 +1,25 @@ +import * as r from 'restructure'; + +let LayerRecord = new r.Struct({ + gid: r.uint16, // Glyph ID of layer glyph (must be in z-order from bottom to top). + paletteIndex: r.uint16 // Index value to use in the appropriate palette. This value must +}); // be less than numPaletteEntries in the CPAL table, except for + // the special case noted below. Each palette entry is 16 bits. + // A palette index of 0xFFFF is a special case indicating that + // the text foreground color should be used. + +let BaseGlyphRecord = new r.Struct({ + gid: r.uint16, // Glyph ID of reference glyph. This glyph is for reference only + // and is not rendered for color. + firstLayerIndex: r.uint16, // Index (from beginning of the Layer Records) to the layer record. + // There will be numLayers consecutive entries for this base glyph. + numLayers: r.uint16 +}); + +export default new r.Struct({ + version: r.uint16, + numBaseGlyphRecords: r.uint16, + baseGlyphRecord: new r.Pointer(r.uint32, new r.Array(BaseGlyphRecord, 'numBaseGlyphRecords')), + layerRecords: new r.Pointer(r.uint32, new r.Array(LayerRecord, 'numLayerRecords'), { lazy: true }), + numLayerRecords: r.uint16 +}); diff --git a/node_modules/fontkit/src/tables/CPAL.js b/node_modules/fontkit/src/tables/CPAL.js new file mode 100644 index 0000000000000000000000000000000000000000..2b4fd9ee80df4e129c2c920ced5fe1413c51859a --- /dev/null +++ b/node_modules/fontkit/src/tables/CPAL.js @@ -0,0 +1,24 @@ +import * as r from 'restructure'; + +let ColorRecord = new r.Struct({ + blue: r.uint8, + green: r.uint8, + red: r.uint8, + alpha: r.uint8 +}); + +export default new r.VersionedStruct(r.uint16, { + header: { + numPaletteEntries: r.uint16, + numPalettes: r.uint16, + numColorRecords: r.uint16, + colorRecords: new r.Pointer(r.uint32, new r.Array(ColorRecord, 'numColorRecords')), + colorRecordIndices: new r.Array(r.uint16, 'numPalettes'), + }, + 0: {}, + 1: { + offsetPaletteTypeArray: new r.Pointer(r.uint32, new r.Array(r.uint32, 'numPalettes')), + offsetPaletteLabelArray: new r.Pointer(r.uint32, new r.Array(r.uint16, 'numPalettes')), + offsetPaletteEntryLabelArray: new r.Pointer(r.uint32, new r.Array(r.uint16, 'numPaletteEntries')) + } +}); diff --git a/node_modules/fontkit/src/tables/DSIG.js b/node_modules/fontkit/src/tables/DSIG.js new file mode 100644 index 0000000000000000000000000000000000000000..660be0c98257b77f5509806d9144252459659b72 --- /dev/null +++ b/node_modules/fontkit/src/tables/DSIG.js @@ -0,0 +1,21 @@ +import * as r from 'restructure'; + +let Signature = new r.Struct({ + format: r.uint32, + length: r.uint32, + offset: r.uint32 +}); + +let SignatureBlock = new r.Struct({ + reserved: new r.Reserved(r.uint16, 2), + cbSignature: r.uint32, // Length (in bytes) of the PKCS#7 packet in pbSignature + signature: new r.Buffer('cbSignature') +}); + +export default new r.Struct({ + ulVersion: r.uint32, // Version number of the DSIG table (0x00000001) + usNumSigs: r.uint16, // Number of signatures in the table + usFlag: r.uint16, // Permission flags + signatures: new r.Array(Signature, 'usNumSigs'), + signatureBlocks: new r.Array(SignatureBlock, 'usNumSigs') +}); diff --git a/node_modules/fontkit/src/tables/EBDT.js b/node_modules/fontkit/src/tables/EBDT.js new file mode 100644 index 0000000000000000000000000000000000000000..c4aa5967baadce1f244ec33269f826670163c7c9 --- /dev/null +++ b/node_modules/fontkit/src/tables/EBDT.js @@ -0,0 +1,91 @@ +import * as r from 'restructure'; + +export let BigMetrics = new r.Struct({ + height: r.uint8, + width: r.uint8, + horiBearingX: r.int8, + horiBearingY: r.int8, + horiAdvance: r.uint8, + vertBearingX: r.int8, + vertBearingY: r.int8, + vertAdvance: r.uint8 +}); + +export let SmallMetrics = new r.Struct({ + height: r.uint8, + width: r.uint8, + bearingX: r.int8, + bearingY: r.int8, + advance: r.uint8 +}); + +let EBDTComponent = new r.Struct({ + glyph: r.uint16, + xOffset: r.int8, + yOffset: r.int8 +}); + +class ByteAligned {} + +class BitAligned {} + +export let glyph = new r.VersionedStruct('version', { + 1: { + metrics: SmallMetrics, + data: ByteAligned + }, + + 2: { + metrics: SmallMetrics, + data: BitAligned + }, + + // format 3 is deprecated + // format 4 is not supported by Microsoft + + 5: { + data: BitAligned + }, + + 6: { + metrics: BigMetrics, + data: ByteAligned + }, + + 7: { + metrics: BigMetrics, + data: BitAligned + }, + + 8: { + metrics: SmallMetrics, + pad: new r.Reserved(r.uint8), + numComponents: r.uint16, + components: new r.Array(EBDTComponent, 'numComponents') + }, + + 9: { + metrics: BigMetrics, + pad: new r.Reserved(r.uint8), + numComponents: r.uint16, + components: new r.Array(EBDTComponent, 'numComponents') + }, + + 17: { + metrics: SmallMetrics, + dataLen: r.uint32, + data: new r.Buffer('dataLen') + }, + + 18: { + metrics: BigMetrics, + dataLen: r.uint32, + data: new r.Buffer('dataLen') + }, + + 19: { + dataLen: r.uint32, + data: new r.Buffer('dataLen') + } +}); + diff --git a/node_modules/fontkit/src/tables/EBLC.js b/node_modules/fontkit/src/tables/EBLC.js new file mode 100644 index 0000000000000000000000000000000000000000..90705ef973c6cbfdf666ae990773c543b1183e1d --- /dev/null +++ b/node_modules/fontkit/src/tables/EBLC.js @@ -0,0 +1,80 @@ +import * as r from 'restructure'; +import {BigMetrics} from './EBDT'; + +let SBitLineMetrics = new r.Struct({ + ascender: r.int8, + descender: r.int8, + widthMax: r.uint8, + caretSlopeNumerator: r.int8, + caretSlopeDenominator: r.int8, + caretOffset: r.int8, + minOriginSB: r.int8, + minAdvanceSB: r.int8, + maxBeforeBL: r.int8, + minAfterBL: r.int8, + pad: new r.Reserved(r.int8, 2) +}); + +let CodeOffsetPair = new r.Struct({ + glyphCode: r.uint16, + offset: r.uint16 +}); + +let IndexSubtable = new r.VersionedStruct(r.uint16, { + header: { + imageFormat: r.uint16, + imageDataOffset: r.uint32 + }, + + 1: { + offsetArray: new r.Array(r.uint32, t => t.parent.lastGlyphIndex - t.parent.firstGlyphIndex + 1) + }, + + 2: { + imageSize: r.uint32, + bigMetrics: BigMetrics + }, + + 3: { + offsetArray: new r.Array(r.uint16, t => t.parent.lastGlyphIndex - t.parent.firstGlyphIndex + 1) + }, + + 4: { + numGlyphs: r.uint32, + glyphArray: new r.Array(CodeOffsetPair, t => t.numGlyphs + 1) + }, + + 5: { + imageSize: r.uint32, + bigMetrics: BigMetrics, + numGlyphs: r.uint32, + glyphCodeArray: new r.Array(r.uint16, 'numGlyphs') + } +}); + +let IndexSubtableArray = new r.Struct({ + firstGlyphIndex: r.uint16, + lastGlyphIndex: r.uint16, + subtable: new r.Pointer(r.uint32, IndexSubtable) +}); + +let BitmapSizeTable = new r.Struct({ + indexSubTableArray: new r.Pointer(r.uint32, new r.Array(IndexSubtableArray, 1), { type: 'parent' }), + indexTablesSize: r.uint32, + numberOfIndexSubTables: r.uint32, + colorRef: r.uint32, + hori: SBitLineMetrics, + vert: SBitLineMetrics, + startGlyphIndex: r.uint16, + endGlyphIndex: r.uint16, + ppemX: r.uint8, + ppemY: r.uint8, + bitDepth: r.uint8, + flags: new r.Bitfield(r.uint8, ['horizontal', 'vertical']) +}); + +export default new r.Struct({ + version: r.uint32, // 0x00020000 + numSizes: r.uint32, + sizes: new r.Array(BitmapSizeTable, 'numSizes') +}); diff --git a/node_modules/fontkit/src/tables/GDEF.js b/node_modules/fontkit/src/tables/GDEF.js new file mode 100644 index 0000000000000000000000000000000000000000..a1be86304ab1c92f84a06a3c7e8a85568d591cb3 --- /dev/null +++ b/node_modules/fontkit/src/tables/GDEF.js @@ -0,0 +1,57 @@ +import * as r from 'restructure'; +import {ScriptList, FeatureList, LookupList, Coverage, ClassDef, Device} from './opentype'; +import {ItemVariationStore} from './variations'; + +let AttachPoint = new r.Array(r.uint16, r.uint16); +let AttachList = new r.Struct({ + coverage: new r.Pointer(r.uint16, Coverage), + glyphCount: r.uint16, + attachPoints: new r.Array(new r.Pointer(r.uint16, AttachPoint), 'glyphCount') +}); + +let CaretValue = new r.VersionedStruct(r.uint16, { + 1: { // Design units only + coordinate: r.int16 + }, + + 2: { // Contour point + caretValuePoint: r.uint16 + }, + + 3: { // Design units plus Device table + coordinate: r.int16, + deviceTable: new r.Pointer(r.uint16, Device) + } +}); + +let LigGlyph = new r.Array(new r.Pointer(r.uint16, CaretValue), r.uint16); + +let LigCaretList = new r.Struct({ + coverage: new r.Pointer(r.uint16, Coverage), + ligGlyphCount: r.uint16, + ligGlyphs: new r.Array(new r.Pointer(r.uint16, LigGlyph), 'ligGlyphCount') +}); + +let MarkGlyphSetsDef = new r.Struct({ + markSetTableFormat: r.uint16, + markSetCount: r.uint16, + coverage: new r.Array(new r.Pointer(r.uint32, Coverage), 'markSetCount') +}); + +export default new r.VersionedStruct(r.uint32, { + header: { + glyphClassDef: new r.Pointer(r.uint16, ClassDef), + attachList: new r.Pointer(r.uint16, AttachList), + ligCaretList: new r.Pointer(r.uint16, LigCaretList), + markAttachClassDef: new r.Pointer(r.uint16, ClassDef) + }, + + 0x00010000: {}, + 0x00010002: { + markGlyphSetsDef: new r.Pointer(r.uint16, MarkGlyphSetsDef) + }, + 0x00010003: { + markGlyphSetsDef: new r.Pointer(r.uint16, MarkGlyphSetsDef), + itemVariationStore: new r.Pointer(r.uint32, ItemVariationStore) + } +}); diff --git a/node_modules/fontkit/src/tables/GPOS.js b/node_modules/fontkit/src/tables/GPOS.js new file mode 100644 index 0000000000000000000000000000000000000000..3fc7cc33a6530f6fd427337656bb869585261be8 --- /dev/null +++ b/node_modules/fontkit/src/tables/GPOS.js @@ -0,0 +1,209 @@ +import * as r from 'restructure'; +import {ScriptList, FeatureList, LookupList, Coverage, ClassDef, Device, Context, ChainingContext} from './opentype'; +import {FeatureVariations} from './variations'; + +let ValueFormat = new r.Bitfield(r.uint16, [ + 'xPlacement', 'yPlacement', + 'xAdvance', 'yAdvance', + 'xPlaDevice', 'yPlaDevice', + 'xAdvDevice', 'yAdvDevice' +]); + +let types = { + xPlacement: r.int16, + yPlacement: r.int16, + xAdvance: r.int16, + yAdvance: r.int16, + xPlaDevice: new r.Pointer(r.uint16, Device, { type: 'global', relativeTo: ctx => ctx.rel }), + yPlaDevice: new r.Pointer(r.uint16, Device, { type: 'global', relativeTo: ctx => ctx.rel }), + xAdvDevice: new r.Pointer(r.uint16, Device, { type: 'global', relativeTo: ctx => ctx.rel }), + yAdvDevice: new r.Pointer(r.uint16, Device, { type: 'global', relativeTo: ctx => ctx.rel }) +}; + +class ValueRecord { + constructor(key = 'valueFormat') { + this.key = key; + } + + buildStruct(parent) { + let struct = parent; + while (!struct[this.key] && struct.parent) { + struct = struct.parent; + } + + if (!struct[this.key]) return; + + let fields = {}; + fields.rel = () => struct._startOffset; + + let format = struct[this.key]; + for (let key in format) { + if (format[key]) { + fields[key] = types[key]; + } + } + + return new r.Struct(fields); + } + + size(val, ctx) { + return this.buildStruct(ctx).size(val, ctx); + } + + decode(stream, parent) { + let res = this.buildStruct(parent).decode(stream, parent); + delete res.rel; + return res; + } +} + +let PairValueRecord = new r.Struct({ + secondGlyph: r.uint16, + value1: new ValueRecord('valueFormat1'), + value2: new ValueRecord('valueFormat2') +}); + +let PairSet = new r.Array(PairValueRecord, r.uint16); + +let Class2Record = new r.Struct({ + value1: new ValueRecord('valueFormat1'), + value2: new ValueRecord('valueFormat2') +}); + +let Anchor = new r.VersionedStruct(r.uint16, { + 1: { // Design units only + xCoordinate: r.int16, + yCoordinate: r.int16 + }, + + 2: { // Design units plus contour point + xCoordinate: r.int16, + yCoordinate: r.int16, + anchorPoint: r.uint16 + }, + + 3: { // Design units plus Device tables + xCoordinate: r.int16, + yCoordinate: r.int16, + xDeviceTable: new r.Pointer(r.uint16, Device), + yDeviceTable: new r.Pointer(r.uint16, Device) + } +}); + +let EntryExitRecord = new r.Struct({ + entryAnchor: new r.Pointer(r.uint16, Anchor, {type: 'parent'}), + exitAnchor: new r.Pointer(r.uint16, Anchor, {type: 'parent'}) +}); + +let MarkRecord = new r.Struct({ + class: r.uint16, + markAnchor: new r.Pointer(r.uint16, Anchor, {type: 'parent'}) +}); + +let MarkArray = new r.Array(MarkRecord, r.uint16); + +let BaseRecord = new r.Array(new r.Pointer(r.uint16, Anchor), t => t.parent.classCount); +let BaseArray = new r.Array(BaseRecord, r.uint16); + +let ComponentRecord = new r.Array(new r.Pointer(r.uint16, Anchor), t => t.parent.parent.classCount); +let LigatureAttach = new r.Array(ComponentRecord, r.uint16); +let LigatureArray = new r.Array(new r.Pointer(r.uint16, LigatureAttach), r.uint16); + +let GPOSLookup = new r.VersionedStruct('lookupType', { + 1: new r.VersionedStruct(r.uint16, { // Single Adjustment + 1: { // Single positioning value + coverage: new r.Pointer(r.uint16, Coverage), + valueFormat: ValueFormat, + value: new ValueRecord() + }, + 2: { + coverage: new r.Pointer(r.uint16, Coverage), + valueFormat: ValueFormat, + valueCount: r.uint16, + values: new r.LazyArray(new ValueRecord(), 'valueCount') + } + }), + + 2: new r.VersionedStruct(r.uint16, { // Pair Adjustment Positioning + 1: { // Adjustments for glyph pairs + coverage: new r.Pointer(r.uint16, Coverage), + valueFormat1: ValueFormat, + valueFormat2: ValueFormat, + pairSetCount: r.uint16, + pairSets: new r.LazyArray(new r.Pointer(r.uint16, PairSet), 'pairSetCount') + }, + + 2: { // Class pair adjustment + coverage: new r.Pointer(r.uint16, Coverage), + valueFormat1: ValueFormat, + valueFormat2: ValueFormat, + classDef1: new r.Pointer(r.uint16, ClassDef), + classDef2: new r.Pointer(r.uint16, ClassDef), + class1Count: r.uint16, + class2Count: r.uint16, + classRecords: new r.LazyArray(new r.LazyArray(Class2Record, 'class2Count'), 'class1Count') + } + }), + + 3: { // Cursive Attachment Positioning + format: r.uint16, + coverage: new r.Pointer(r.uint16, Coverage), + entryExitCount: r.uint16, + entryExitRecords: new r.Array(EntryExitRecord, 'entryExitCount') + }, + + 4: { // MarkToBase Attachment Positioning + format: r.uint16, + markCoverage: new r.Pointer(r.uint16, Coverage), + baseCoverage: new r.Pointer(r.uint16, Coverage), + classCount: r.uint16, + markArray: new r.Pointer(r.uint16, MarkArray), + baseArray: new r.Pointer(r.uint16, BaseArray) + }, + + 5: { // MarkToLigature Attachment Positioning + format: r.uint16, + markCoverage: new r.Pointer(r.uint16, Coverage), + ligatureCoverage: new r.Pointer(r.uint16, Coverage), + classCount: r.uint16, + markArray: new r.Pointer(r.uint16, MarkArray), + ligatureArray: new r.Pointer(r.uint16, LigatureArray) + }, + + 6: { // MarkToMark Attachment Positioning + format: r.uint16, + mark1Coverage: new r.Pointer(r.uint16, Coverage), + mark2Coverage: new r.Pointer(r.uint16, Coverage), + classCount: r.uint16, + mark1Array: new r.Pointer(r.uint16, MarkArray), + mark2Array: new r.Pointer(r.uint16, BaseArray) + }, + + 7: Context, // Contextual positioning + 8: ChainingContext, // Chaining contextual positioning + + 9: { // Extension Positioning + posFormat: r.uint16, + lookupType: r.uint16, // cannot also be 9 + extension: new r.Pointer(r.uint32, null) + } +}); + +// Fix circular reference +GPOSLookup.versions[9].extension.type = GPOSLookup; + +export default new r.VersionedStruct(r.uint32, { + header: { + scriptList: new r.Pointer(r.uint16, ScriptList), + featureList: new r.Pointer(r.uint16, FeatureList), + lookupList: new r.Pointer(r.uint16, new LookupList(GPOSLookup)) + }, + + 0x00010000: {}, + 0x00010001: { + featureVariations: new r.Pointer(r.uint32, FeatureVariations) + } +}); + +// export GPOSLookup for JSTF table +export { GPOSLookup }; diff --git a/node_modules/fontkit/src/tables/GSUB.js b/node_modules/fontkit/src/tables/GSUB.js new file mode 100644 index 0000000000000000000000000000000000000000..757bf5a139a0cee4a0999102d2443d70e2dd5469 --- /dev/null +++ b/node_modules/fontkit/src/tables/GSUB.js @@ -0,0 +1,84 @@ +import * as r from 'restructure'; +import {ScriptList, FeatureList, LookupList, Coverage, ClassDef, Device, Context, ChainingContext} from './opentype'; +import {FeatureVariations} from './variations'; + +let Sequence = new r.Array(r.uint16, r.uint16); +let AlternateSet = Sequence; + +let Ligature = new r.Struct({ + glyph: r.uint16, + compCount: r.uint16, + components: new r.Array(r.uint16, t => t.compCount - 1) +}); + +let LigatureSet = new r.Array(new r.Pointer(r.uint16, Ligature), r.uint16); + +let GSUBLookup = new r.VersionedStruct('lookupType', { + 1: new r.VersionedStruct(r.uint16, {// Single Substitution + 1: { + coverage: new r.Pointer(r.uint16, Coverage), + deltaGlyphID: r.int16 + }, + 2: { + coverage: new r.Pointer(r.uint16, Coverage), + glyphCount: r.uint16, + substitute: new r.LazyArray(r.uint16, 'glyphCount') + } + }), + + 2: { // Multiple Substitution + substFormat: r.uint16, + coverage: new r.Pointer(r.uint16, Coverage), + count: r.uint16, + sequences: new r.LazyArray(new r.Pointer(r.uint16, Sequence), 'count') + }, + + 3: { // Alternate Substitution + substFormat: r.uint16, + coverage: new r.Pointer(r.uint16, Coverage), + count: r.uint16, + alternateSet: new r.LazyArray(new r.Pointer(r.uint16, AlternateSet), 'count') + }, + + 4: { // Ligature Substitution + substFormat: r.uint16, + coverage: new r.Pointer(r.uint16, Coverage), + count: r.uint16, + ligatureSets: new r.LazyArray(new r.Pointer(r.uint16, LigatureSet), 'count') + }, + + 5: Context, // Contextual Substitution + 6: ChainingContext, // Chaining Contextual Substitution + + 7: { // Extension Substitution + substFormat: r.uint16, + lookupType: r.uint16, // cannot also be 7 + extension: new r.Pointer(r.uint32, null) + }, + + 8: { // Reverse Chaining Contextual Single Substitution + substFormat: r.uint16, + coverage: new r.Pointer(r.uint16, Coverage), + backtrackCoverage: new r.Array(new r.Pointer(r.uint16, Coverage), 'backtrackGlyphCount'), + lookaheadGlyphCount: r.uint16, + lookaheadCoverage: new r.Array(new r.Pointer(r.uint16, Coverage), 'lookaheadGlyphCount'), + glyphCount: r.uint16, + substitutes: new r.Array(r.uint16, 'glyphCount') + } +}); + +// Fix circular reference +GSUBLookup.versions[7].extension.type = GSUBLookup; + +export default new r.VersionedStruct(r.uint32, { + header: { + scriptList: new r.Pointer(r.uint16, ScriptList), + featureList: new r.Pointer(r.uint16, FeatureList), + lookupList: new r.Pointer(r.uint16, new LookupList(GSUBLookup)) + }, + + 0x00010000: {}, + 0x00010001: { + featureVariations: new r.Pointer(r.uint32, FeatureVariations) + } +}); diff --git a/node_modules/fontkit/src/tables/HVAR.js b/node_modules/fontkit/src/tables/HVAR.js new file mode 100644 index 0000000000000000000000000000000000000000..0b45e95874b89e455ece95c44219b060a0edd686 --- /dev/null +++ b/node_modules/fontkit/src/tables/HVAR.js @@ -0,0 +1,44 @@ +import * as r from 'restructure'; +import { resolveLength } from 'restructure'; +import { ItemVariationStore } from './variations'; + +// TODO: add this to restructure +class VariableSizeNumber { + constructor(size) { + this._size = size; + } + + decode(stream, parent) { + switch (this.size(0, parent)) { + case 1: return stream.readUInt8(); + case 2: return stream.readUInt16BE(); + case 3: return stream.readUInt24BE(); + case 4: return stream.readUInt32BE(); + } + } + + size(val, parent) { + return resolveLength(this._size, null, parent); + } +} + +let MapDataEntry = new r.Struct({ + entry: new VariableSizeNumber(t => ((t.parent.entryFormat & 0x0030) >> 4) + 1), + outerIndex: t => t.entry >> ((t.parent.entryFormat & 0x000F) + 1), + innerIndex: t => t.entry & ((1 << ((t.parent.entryFormat & 0x000F) + 1)) - 1) +}); + +let DeltaSetIndexMap = new r.Struct({ + entryFormat: r.uint16, + mapCount: r.uint16, + mapData: new r.Array(MapDataEntry, 'mapCount') +}); + +export default new r.Struct({ + majorVersion: r.uint16, + minorVersion: r.uint16, + itemVariationStore: new r.Pointer(r.uint32, ItemVariationStore), + advanceWidthMapping: new r.Pointer(r.uint32, DeltaSetIndexMap), + LSBMapping: new r.Pointer(r.uint32, DeltaSetIndexMap), + RSBMapping: new r.Pointer(r.uint32, DeltaSetIndexMap) +}); diff --git a/node_modules/fontkit/src/tables/JSTF.js b/node_modules/fontkit/src/tables/JSTF.js new file mode 100644 index 0000000000000000000000000000000000000000..abfbe948e713eca11fa7758c4b8d2182b1f56f75 --- /dev/null +++ b/node_modules/fontkit/src/tables/JSTF.js @@ -0,0 +1,43 @@ +import * as r from 'restructure'; +import { ScriptList, FeatureList, LookupList, Coverage, ClassDef, Device } from './opentype'; +import { GPOSLookup } from './GPOS'; + +let JstfGSUBModList = new r.Array(r.uint16, r.uint16); + +let JstfPriority = new r.Struct({ + shrinkageEnableGSUB: new r.Pointer(r.uint16, JstfGSUBModList), + shrinkageDisableGSUB: new r.Pointer(r.uint16, JstfGSUBModList), + shrinkageEnableGPOS: new r.Pointer(r.uint16, JstfGSUBModList), + shrinkageDisableGPOS: new r.Pointer(r.uint16, JstfGSUBModList), + shrinkageJstfMax: new r.Pointer(r.uint16, new LookupList(GPOSLookup)), + extensionEnableGSUB: new r.Pointer(r.uint16, JstfGSUBModList), + extensionDisableGSUB: new r.Pointer(r.uint16, JstfGSUBModList), + extensionEnableGPOS: new r.Pointer(r.uint16, JstfGSUBModList), + extensionDisableGPOS: new r.Pointer(r.uint16, JstfGSUBModList), + extensionJstfMax: new r.Pointer(r.uint16, new LookupList(GPOSLookup)) +}); + +let JstfLangSys = new r.Array(new r.Pointer(r.uint16, JstfPriority), r.uint16); + +let JstfLangSysRecord = new r.Struct({ + tag: new r.String(4), + jstfLangSys: new r.Pointer(r.uint16, JstfLangSys) +}); + +let JstfScript = new r.Struct({ + extenderGlyphs: new r.Pointer(r.uint16, new r.Array(r.uint16, r.uint16)), // array of glyphs to extend line length + defaultLangSys: new r.Pointer(r.uint16, JstfLangSys), + langSysCount: r.uint16, + langSysRecords: new r.Array(JstfLangSysRecord, 'langSysCount') +}); + +let JstfScriptRecord = new r.Struct({ + tag: new r.String(4), + script: new r.Pointer(r.uint16, JstfScript, {type: 'parent'}) +}); + +export default new r.Struct({ + version: r.uint32, // should be 0x00010000 + scriptCount: r.uint16, + scriptList: new r.Array(JstfScriptRecord, 'scriptCount') +}); diff --git a/node_modules/fontkit/src/tables/LTSH.js b/node_modules/fontkit/src/tables/LTSH.js new file mode 100644 index 0000000000000000000000000000000000000000..8a7c29a8f62ce494b356b49b66cc416c2c080504 --- /dev/null +++ b/node_modules/fontkit/src/tables/LTSH.js @@ -0,0 +1,10 @@ +import * as r from 'restructure'; + +// Linear Threshold table +// Records the ppem for each glyph at which the scaling becomes linear again, +// despite instructions effecting the advance width +export default new r.Struct({ + version: r.uint16, + numGlyphs: r.uint16, + yPels: new r.Array(r.uint8, 'numGlyphs') +}); diff --git a/node_modules/fontkit/src/tables/OS2.js b/node_modules/fontkit/src/tables/OS2.js new file mode 100644 index 0000000000000000000000000000000000000000..931a0e98ab03f51f19ef9afc621114b4ed386dfe --- /dev/null +++ b/node_modules/fontkit/src/tables/OS2.js @@ -0,0 +1,84 @@ +import * as r from 'restructure'; + +var OS2 = new r.VersionedStruct(r.uint16, { + header: { + xAvgCharWidth: r.int16, // average weighted advance width of lower case letters and space + usWeightClass: r.uint16, // visual weight of stroke in glyphs + usWidthClass: r.uint16, // relative change from the normal aspect ratio (width to height ratio) + fsType: new r.Bitfield(r.uint16, [ // Indicates font embedding licensing rights + null, 'noEmbedding', 'viewOnly', 'editable', null, + null, null, null, 'noSubsetting', 'bitmapOnly' + ]), + ySubscriptXSize: r.int16, // recommended horizontal size in pixels for subscripts + ySubscriptYSize: r.int16, // recommended vertical size in pixels for subscripts + ySubscriptXOffset: r.int16, // recommended horizontal offset for subscripts + ySubscriptYOffset: r.int16, // recommended vertical offset form the baseline for subscripts + ySuperscriptXSize: r.int16, // recommended horizontal size in pixels for superscripts + ySuperscriptYSize: r.int16, // recommended vertical size in pixels for superscripts + ySuperscriptXOffset: r.int16, // recommended horizontal offset for superscripts + ySuperscriptYOffset: r.int16, // recommended vertical offset from the baseline for superscripts + yStrikeoutSize: r.int16, // width of the strikeout stroke + yStrikeoutPosition: r.int16, // position of the strikeout stroke relative to the baseline + sFamilyClass: r.int16, // classification of font-family design + panose: new r.Array(r.uint8, 10), // describe the visual characteristics of a given typeface + ulCharRange: new r.Array(r.uint32, 4), + vendorID: new r.String(4), // four character identifier for the font vendor + fsSelection: new r.Bitfield(r.uint16, [ // bit field containing information about the font + 'italic', 'underscore', 'negative', 'outlined', 'strikeout', + 'bold', 'regular', 'useTypoMetrics', 'wws', 'oblique' + ]), + usFirstCharIndex: r.uint16, // The minimum Unicode index in this font + usLastCharIndex: r.uint16 // The maximum Unicode index in this font + }, + + // The Apple version of this table ends here, but the Microsoft one continues on... + 0: {}, + + 1: { + typoAscender: r.int16, + typoDescender: r.int16, + typoLineGap: r.int16, + winAscent: r.uint16, + winDescent: r.uint16, + codePageRange: new r.Array(r.uint32, 2) + }, + + 2: { + // these should be common with version 1 somehow + typoAscender: r.int16, + typoDescender: r.int16, + typoLineGap: r.int16, + winAscent: r.uint16, + winDescent: r.uint16, + codePageRange: new r.Array(r.uint32, 2), + + xHeight: r.int16, + capHeight: r.int16, + defaultChar: r.uint16, + breakChar: r.uint16, + maxContent: r.uint16 + }, + + 5: { + typoAscender: r.int16, + typoDescender: r.int16, + typoLineGap: r.int16, + winAscent: r.uint16, + winDescent: r.uint16, + codePageRange: new r.Array(r.uint32, 2), + + xHeight: r.int16, + capHeight: r.int16, + defaultChar: r.uint16, + breakChar: r.uint16, + maxContent: r.uint16, + + usLowerOpticalPointSize: r.uint16, + usUpperOpticalPointSize: r.uint16 + } +}); + +let versions = OS2.versions; +versions[3] = versions[4] = versions[2]; + +export default OS2; diff --git a/node_modules/fontkit/src/tables/PCLT.js b/node_modules/fontkit/src/tables/PCLT.js new file mode 100644 index 0000000000000000000000000000000000000000..5df584d94844e2640b1cb6ce7b866e3a019cb1c2 --- /dev/null +++ b/node_modules/fontkit/src/tables/PCLT.js @@ -0,0 +1,21 @@ +import * as r from 'restructure'; + +// PCL 5 Table +// NOTE: The PCLT table is strongly discouraged for OpenType fonts with TrueType outlines +export default new r.Struct({ + version: r.uint16, + fontNumber: r.uint32, + pitch: r.uint16, + xHeight: r.uint16, + style: r.uint16, + typeFamily: r.uint16, + capHeight: r.uint16, + symbolSet: r.uint16, + typeface: new r.String(16), + characterComplement: new r.String(8), + fileName: new r.String(6), + strokeWeight: new r.String(1), + widthType: new r.String(1), + serifStyle: r.uint8, + reserved: new r.Reserved(r.uint8) +}); diff --git a/node_modules/fontkit/src/tables/VDMX.js b/node_modules/fontkit/src/tables/VDMX.js new file mode 100644 index 0000000000000000000000000000000000000000..c65e658405f824bb09c5fbd3bb15d8c025c6f21d --- /dev/null +++ b/node_modules/fontkit/src/tables/VDMX.js @@ -0,0 +1,33 @@ +import * as r from 'restructure'; + +// VDMX tables contain ascender/descender overrides for certain (usually small) +// sizes. This is needed in order to match font metrics on Windows. + +let Ratio = new r.Struct({ + bCharSet: r.uint8, // Character set + xRatio: r.uint8, // Value to use for x-Ratio + yStartRatio: r.uint8, // Starting y-Ratio value + yEndRatio: r.uint8 // Ending y-Ratio value +}); + +let vTable = new r.Struct({ + yPelHeight: r.uint16, // yPelHeight to which values apply + yMax: r.int16, // Maximum value (in pels) for this yPelHeight + yMin: r.int16 // Minimum value (in pels) for this yPelHeight +}); + +let VdmxGroup = new r.Struct({ + recs: r.uint16, // Number of height records in this group + startsz: r.uint8, // Starting yPelHeight + endsz: r.uint8, // Ending yPelHeight + entries: new r.Array(vTable, 'recs') // The VDMX records +}); + +export default new r.Struct({ + version: r.uint16, // Version number (0 or 1) + numRecs: r.uint16, // Number of VDMX groups present + numRatios: r.uint16, // Number of aspect ratio groupings + ratioRanges: new r.Array(Ratio, 'numRatios'), // Ratio ranges + offsets: new r.Array(r.uint16, 'numRatios'), // Offset to the VDMX group for this ratio range + groups: new r.Array(VdmxGroup, 'numRecs') // The actual VDMX groupings +}); diff --git a/node_modules/fontkit/src/tables/VORG.js b/node_modules/fontkit/src/tables/VORG.js new file mode 100644 index 0000000000000000000000000000000000000000..2a4f44067d5c3d2fef583cab7716f9463972cadd --- /dev/null +++ b/node_modules/fontkit/src/tables/VORG.js @@ -0,0 +1,14 @@ +import * as r from 'restructure'; + +let VerticalOrigin = new r.Struct({ + glyphIndex: r.uint16, + vertOriginY: r.int16 +}); + +export default new r.Struct({ + majorVersion: r.uint16, + minorVersion: r.uint16, + defaultVertOriginY: r.int16, + numVertOriginYMetrics: r.uint16, + metrics: new r.Array(VerticalOrigin, 'numVertOriginYMetrics') +}); diff --git a/node_modules/fontkit/src/tables/WOFF2Directory.js b/node_modules/fontkit/src/tables/WOFF2Directory.js new file mode 100644 index 0000000000000000000000000000000000000000..91b10531db020d05fde3bf3862e16a85005a8f71 --- /dev/null +++ b/node_modules/fontkit/src/tables/WOFF2Directory.js @@ -0,0 +1,74 @@ +import * as r from 'restructure'; + +const Base128 = { + decode(stream) { + let result = 0; + let iterable = [0, 1, 2, 3, 4]; + for (let j = 0; j < iterable.length; j++) { + let i = iterable[j]; + let code = stream.readUInt8(); + + // If any of the top seven bits are set then we're about to overflow. + if (result & 0xe0000000) { + throw new Error('Overflow'); + } + + result = (result << 7) | (code & 0x7f); + if ((code & 0x80) === 0) { + return result; + } + } + + throw new Error('Bad base 128 number'); + } +}; + +let knownTags = [ + 'cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', + 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG', 'EBDT', 'EBLC', 'gasp', + 'hdmx', 'kern', 'LTSH', 'PCLT', 'VDMX', 'vhea', 'vmtx', 'BASE', 'GDEF', + 'GPOS', 'GSUB', 'EBSC', 'JSTF', 'MATH', 'CBDT', 'CBLC', 'COLR', 'CPAL', + 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', + 'feat', 'fmtx', 'fvar', 'gvar', 'hsty', 'just', 'lcar', 'mort', 'morx', + 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill' +]; + +let WOFF2DirectoryEntry = new r.Struct({ + flags: r.uint8, + customTag: new r.Optional(new r.String(4), t => (t.flags & 0x3f) === 0x3f), + tag: t => t.customTag || knownTags[t.flags & 0x3f],// || (() => { throw new Error(`Bad tag: ${flags & 0x3f}`); })(); }, + length: Base128, + transformVersion: t => (t.flags >>> 6) & 0x03, + transformed: t => (t.tag === 'glyf' || t.tag === 'loca') ? t.transformVersion === 0 : t.transformVersion !== 0, + transformLength: new r.Optional(Base128, t => t.transformed) +}); + +let WOFF2Directory = new r.Struct({ + tag: new r.String(4), // should be 'wOF2' + flavor: r.uint32, + length: r.uint32, + numTables: r.uint16, + reserved: new r.Reserved(r.uint16), + totalSfntSize: r.uint32, + totalCompressedSize: r.uint32, + majorVersion: r.uint16, + minorVersion: r.uint16, + metaOffset: r.uint32, + metaLength: r.uint32, + metaOrigLength: r.uint32, + privOffset: r.uint32, + privLength: r.uint32, + tables: new r.Array(WOFF2DirectoryEntry, 'numTables') +}); + +WOFF2Directory.process = function() { + let tables = {}; + for (let i = 0; i < this.tables.length; i++) { + let table = this.tables[i]; + tables[table.tag] = table; + } + + return this.tables = tables; +}; + +export default WOFF2Directory; diff --git a/node_modules/fontkit/src/tables/WOFFDirectory.js b/node_modules/fontkit/src/tables/WOFFDirectory.js new file mode 100644 index 0000000000000000000000000000000000000000..dfd5d55d9127a713ef5a295af6cbf2915bd99426 --- /dev/null +++ b/node_modules/fontkit/src/tables/WOFFDirectory.js @@ -0,0 +1,38 @@ +import * as r from 'restructure'; +import tables from './'; + +let WOFFDirectoryEntry = new r.Struct({ + tag: new r.String(4), + offset: new r.Pointer(r.uint32, 'void', {type: 'global'}), + compLength: r.uint32, + length: r.uint32, + origChecksum: r.uint32 +}); + +let WOFFDirectory = new r.Struct({ + tag: new r.String(4), // should be 'wOFF' + flavor: r.uint32, + length: r.uint32, + numTables: r.uint16, + reserved: new r.Reserved(r.uint16), + totalSfntSize: r.uint32, + majorVersion: r.uint16, + minorVersion: r.uint16, + metaOffset: r.uint32, + metaLength: r.uint32, + metaOrigLength: r.uint32, + privOffset: r.uint32, + privLength: r.uint32, + tables: new r.Array(WOFFDirectoryEntry, 'numTables') +}); + +WOFFDirectory.process = function() { + let tables = {}; + for (let table of this.tables) { + tables[table.tag] = table; + } + + this.tables = tables; +}; + +export default WOFFDirectory; diff --git a/node_modules/fontkit/src/tables/aat.js b/node_modules/fontkit/src/tables/aat.js new file mode 100644 index 0000000000000000000000000000000000000000..299621ba06d20345126e96b5088bb6ae8b41bda3 --- /dev/null +++ b/node_modules/fontkit/src/tables/aat.js @@ -0,0 +1,157 @@ +import * as r from 'restructure'; + +class UnboundedArrayAccessor { + constructor(type, stream, parent) { + this.type = type; + this.stream = stream; + this.parent = parent; + this.base = this.stream.pos; + this._items = []; + } + + getItem(index) { + if (this._items[index] == null) { + let pos = this.stream.pos; + this.stream.pos = this.base + this.type.size(null, this.parent) * index; + this._items[index] = this.type.decode(this.stream, this.parent); + this.stream.pos = pos; + } + + return this._items[index]; + } + + inspect() { + return `[UnboundedArray ${this.type.constructor.name}]`; + } +} + +export class UnboundedArray extends r.Array { + constructor(type) { + super(type, 0); + } + + decode(stream, parent) { + return new UnboundedArrayAccessor(this.type, stream, parent); + } +} + +export let LookupTable = function(ValueType = r.uint16) { + // Helper class that makes internal structures invisible to pointers + class Shadow { + constructor(type) { + this.type = type; + } + + decode(stream, ctx) { + ctx = ctx.parent.parent; + return this.type.decode(stream, ctx); + } + + size(val, ctx) { + ctx = ctx.parent.parent; + return this.type.size(val, ctx); + } + + encode(stream, val, ctx) { + ctx = ctx.parent.parent; + return this.type.encode(stream, val, ctx); + } + } + + ValueType = new Shadow(ValueType); + + let BinarySearchHeader = new r.Struct({ + unitSize: r.uint16, + nUnits: r.uint16, + searchRange: r.uint16, + entrySelector: r.uint16, + rangeShift: r.uint16 + }); + + let LookupSegmentSingle = new r.Struct({ + lastGlyph: r.uint16, + firstGlyph: r.uint16, + value: ValueType + }); + + let LookupSegmentArray = new r.Struct({ + lastGlyph: r.uint16, + firstGlyph: r.uint16, + values: new r.Pointer(r.uint16, new r.Array(ValueType, t => t.lastGlyph - t.firstGlyph + 1), {type: 'parent'}) + }); + + let LookupSingle = new r.Struct({ + glyph: r.uint16, + value: ValueType + }); + + return new r.VersionedStruct(r.uint16, { + 0: { + values: new UnboundedArray(ValueType) // length == number of glyphs maybe? + }, + 2: { + binarySearchHeader: BinarySearchHeader, + segments: new r.Array(LookupSegmentSingle, t => t.binarySearchHeader.nUnits) + }, + 4: { + binarySearchHeader: BinarySearchHeader, + segments: new r.Array(LookupSegmentArray, t => t.binarySearchHeader.nUnits) + }, + 6: { + binarySearchHeader: BinarySearchHeader, + segments: new r.Array(LookupSingle, t => t.binarySearchHeader.nUnits) + }, + 8: { + firstGlyph: r.uint16, + count: r.uint16, + values: new r.Array(ValueType, 'count') + } + }); +}; + +export function StateTable(entryData = {}, lookupType = r.uint16) { + let entry = Object.assign({ + newState: r.uint16, + flags: r.uint16 + }, entryData); + + let Entry = new r.Struct(entry); + let StateArray = new UnboundedArray(new r.Array(r.uint16, t => t.nClasses)); + + let StateHeader = new r.Struct({ + nClasses: r.uint32, + classTable: new r.Pointer(r.uint32, new LookupTable(lookupType)), + stateArray: new r.Pointer(r.uint32, StateArray), + entryTable: new r.Pointer(r.uint32, new UnboundedArray(Entry)) + }); + + return StateHeader; +} + +// This is the old version of the StateTable structure +export function StateTable1(entryData = {}, lookupType = r.uint16) { + let ClassLookupTable = new r.Struct({ + version() { return 8; }, // simulate LookupTable + firstGlyph: r.uint16, + values: new r.Array(r.uint8, r.uint16) + }); + + let entry = Object.assign({ + newStateOffset: r.uint16, + // convert offset to stateArray index + newState: t => (t.newStateOffset - (t.parent.stateArray.base - t.parent._startOffset)) / t.parent.nClasses, + flags: r.uint16 + }, entryData); + + let Entry = new r.Struct(entry); + let StateArray = new UnboundedArray(new r.Array(r.uint8, t => t.nClasses)); + + let StateHeader1 = new r.Struct({ + nClasses: r.uint16, + classTable: new r.Pointer(r.uint16, ClassLookupTable), + stateArray: new r.Pointer(r.uint16, StateArray), + entryTable: new r.Pointer(r.uint16, new UnboundedArray(Entry)) + }); + + return StateHeader1; +} diff --git a/node_modules/fontkit/src/tables/avar.js b/node_modules/fontkit/src/tables/avar.js new file mode 100644 index 0000000000000000000000000000000000000000..d2e5aef1341ed6ac1f3c46b3b7203aba25c4174c --- /dev/null +++ b/node_modules/fontkit/src/tables/avar.js @@ -0,0 +1,19 @@ +import * as r from 'restructure'; + +let shortFrac = new r.Fixed(16, 'BE', 14); + +let Correspondence = new r.Struct({ + fromCoord: shortFrac, + toCoord: shortFrac +}); + +let Segment = new r.Struct({ + pairCount: r.uint16, + correspondence: new r.Array(Correspondence, 'pairCount') +}); + +export default new r.Struct({ + version: r.fixed32, + axisCount: r.uint32, + segment: new r.Array(Segment, 'axisCount') +}); diff --git a/node_modules/fontkit/src/tables/bsln.js b/node_modules/fontkit/src/tables/bsln.js new file mode 100644 index 0000000000000000000000000000000000000000..21d57547dc0f1c7a48740a887343f6bfbb56fac7 --- /dev/null +++ b/node_modules/fontkit/src/tables/bsln.js @@ -0,0 +1,31 @@ +import * as r from 'restructure'; +import { LookupTable } from './aat'; + +let BslnSubtable = new r.VersionedStruct('format', { + 0: { // Distance-based, no mapping + deltas: new r.Array(r.int16, 32) + }, + + 1: { // Distance-based, with mapping + deltas: new r.Array(r.int16, 32), + mappingData: new LookupTable(r.uint16) + }, + + 2: { // Control point-based, no mapping + standardGlyph: r.uint16, + controlPoints: new r.Array(r.uint16, 32) + }, + + 3: { // Control point-based, with mapping + standardGlyph: r.uint16, + controlPoints: new r.Array(r.uint16, 32), + mappingData: new LookupTable(r.uint16) + } +}); + +export default new r.Struct({ + version: r.fixed32, + format: r.uint16, + defaultBaseline: r.uint16, + subtable: BslnSubtable +}); diff --git a/node_modules/fontkit/src/tables/cmap.js b/node_modules/fontkit/src/tables/cmap.js new file mode 100644 index 0000000000000000000000000000000000000000..0049e45591ba2e14d1faa92e4553b423365d9cd3 --- /dev/null +++ b/node_modules/fontkit/src/tables/cmap.js @@ -0,0 +1,127 @@ +import * as r from 'restructure'; + +let SubHeader = new r.Struct({ + firstCode: r.uint16, + entryCount: r.uint16, + idDelta: r.int16, + idRangeOffset: r.uint16 +}); + +let CmapGroup = new r.Struct({ + startCharCode: r.uint32, + endCharCode: r.uint32, + glyphID: r.uint32 +}); + +let UnicodeValueRange = new r.Struct({ + startUnicodeValue: r.uint24, + additionalCount: r.uint8 +}); + +let UVSMapping = new r.Struct({ + unicodeValue: r.uint24, + glyphID: r.uint16 +}); + +let DefaultUVS = new r.Array(UnicodeValueRange, r.uint32); +let NonDefaultUVS = new r.Array(UVSMapping, r.uint32); + +let VarSelectorRecord = new r.Struct({ + varSelector: r.uint24, + defaultUVS: new r.Pointer(r.uint32, DefaultUVS, {type: 'parent'}), + nonDefaultUVS: new r.Pointer(r.uint32, NonDefaultUVS, {type: 'parent'}) +}); + +let CmapSubtable = new r.VersionedStruct(r.uint16, { + 0: { // Byte encoding + length: r.uint16, // Total table length in bytes (set to 262 for format 0) + language: r.uint16, // Language code for this encoding subtable, or zero if language-independent + codeMap: new r.LazyArray(r.uint8, 256) + }, + + 2: { // High-byte mapping (CJK) + length: r.uint16, + language: r.uint16, + subHeaderKeys: new r.Array(r.uint16, 256), + subHeaderCount: t => Math.max.apply(Math, t.subHeaderKeys), + subHeaders: new r.LazyArray(SubHeader, 'subHeaderCount'), + glyphIndexArray: new r.LazyArray(r.uint16, 'subHeaderCount') + }, + + 4: { // Segment mapping to delta values + length: r.uint16, // Total table length in bytes + language: r.uint16, // Language code + segCountX2: r.uint16, + segCount: t => t.segCountX2 >> 1, + searchRange: r.uint16, + entrySelector: r.uint16, + rangeShift: r.uint16, + endCode: new r.LazyArray(r.uint16, 'segCount'), + reservedPad: new r.Reserved(r.uint16), // This value should be zero + startCode: new r.LazyArray(r.uint16, 'segCount'), + idDelta: new r.LazyArray(r.int16, 'segCount'), + idRangeOffset: new r.LazyArray(r.uint16, 'segCount'), + glyphIndexArray: new r.LazyArray(r.uint16, t => (t.length - t._currentOffset) / 2) + }, + + 6: { // Trimmed table + length: r.uint16, + language: r.uint16, + firstCode: r.uint16, + entryCount: r.uint16, + glyphIndices: new r.LazyArray(r.uint16, 'entryCount') + }, + + 8: { // mixed 16-bit and 32-bit coverage + reserved: new r.Reserved(r.uint16), + length: r.uint32, + language: r.uint16, + is32: new r.LazyArray(r.uint8, 8192), + nGroups: r.uint32, + groups: new r.LazyArray(CmapGroup, 'nGroups') + }, + + 10: { // Trimmed Array + reserved: new r.Reserved(r.uint16), + length: r.uint32, + language: r.uint32, + firstCode: r.uint32, + entryCount: r.uint32, + glyphIndices: new r.LazyArray(r.uint16, 'numChars') + }, + + 12: { // Segmented coverage + reserved: new r.Reserved(r.uint16), + length: r.uint32, + language: r.uint32, + nGroups: r.uint32, + groups: new r.LazyArray(CmapGroup, 'nGroups') + }, + + 13: { // Many-to-one range mappings (same as 12 except for group.startGlyphID) + reserved: new r.Reserved(r.uint16), + length: r.uint32, + language: r.uint32, + nGroups: r.uint32, + groups: new r.LazyArray(CmapGroup, 'nGroups') + }, + + 14: { // Unicode Variation Sequences + length: r.uint32, + numRecords: r.uint32, + varSelectors: new r.LazyArray(VarSelectorRecord, 'numRecords') + } +}); + +let CmapEntry = new r.Struct({ + platformID: r.uint16, // Platform identifier + encodingID: r.uint16, // Platform-specific encoding identifier + table: new r.Pointer(r.uint32, CmapSubtable, {type: 'parent', lazy: true}) +}); + +// character to glyph mapping +export default new r.Struct({ + version: r.uint16, + numSubtables: r.uint16, + tables: new r.Array(CmapEntry, 'numSubtables') +}); diff --git a/node_modules/fontkit/src/tables/cvt.js b/node_modules/fontkit/src/tables/cvt.js new file mode 100644 index 0000000000000000000000000000000000000000..48eecc381f4edf7181537999d88265a98f16547d --- /dev/null +++ b/node_modules/fontkit/src/tables/cvt.js @@ -0,0 +1,6 @@ +import * as r from 'restructure'; + +// An array of predefined values accessible by instructions +export default new r.Struct({ + controlValues: new r.Array(r.int16) +}); diff --git a/node_modules/fontkit/src/tables/directory.js b/node_modules/fontkit/src/tables/directory.js new file mode 100644 index 0000000000000000000000000000000000000000..c95b8c6ace552345fc31cdd85488375dfd88deb6 --- /dev/null +++ b/node_modules/fontkit/src/tables/directory.js @@ -0,0 +1,58 @@ +import * as r from 'restructure'; +import Tables from './'; + +let TableEntry = new r.Struct({ + tag: new r.String(4), + checkSum: r.uint32, + offset: new r.Pointer(r.uint32, 'void', { type: 'global' }), + length: r.uint32 +}); + +let Directory = new r.Struct({ + tag: new r.String(4), + numTables: r.uint16, + searchRange: r.uint16, + entrySelector: r.uint16, + rangeShift: r.uint16, + tables: new r.Array(TableEntry, 'numTables') +}); + +Directory.process = function() { + let tables = {}; + for (let table of this.tables) { + tables[table.tag] = table; + } + + this.tables = tables; +}; + +Directory.preEncode = function() { + if (!Array.isArray(this.tables)) { + let tables = []; + for (let tag in this.tables) { + let table = this.tables[tag]; + if (table) { + tables.push({ + tag: tag, + checkSum: 0, + offset: new r.VoidPointer(Tables[tag], table), + length: Tables[tag].size(table) + }); + } + } + + this.tables = tables; + } + + this.tag = 'true'; + this.numTables = this.tables.length; + + let maxExponentFor2 = Math.floor((Math.log(this.numTables) / Math.LN2)); + let maxPowerOf2 = Math.pow(2, maxExponentFor2); + + this.searchRange = maxPowerOf2 * 16; + this.entrySelector = Math.log(maxPowerOf2) / Math.LN2; + this.rangeShift = this.numTables * 16 - this.searchRange; +}; + +export default Directory; diff --git a/node_modules/fontkit/src/tables/feat.js b/node_modules/fontkit/src/tables/feat.js new file mode 100644 index 0000000000000000000000000000000000000000..bfbbfb27227b5396bfd22e98ba4b8ebbb4379273 --- /dev/null +++ b/node_modules/fontkit/src/tables/feat.js @@ -0,0 +1,28 @@ +import * as r from 'restructure'; + +let Setting = new r.Struct({ + setting: r.uint16, + nameIndex: r.int16, + name: t => t.parent.parent.parent.name.records.fontFeatures[t.nameIndex] +}); + +let FeatureName = new r.Struct({ + feature: r.uint16, + nSettings: r.uint16, + settingTable: new r.Pointer(r.uint32, new r.Array(Setting, 'nSettings'), { type: 'parent' }), + featureFlags: new r.Bitfield(r.uint8, [ + null, null, null, null, null, null, + 'hasDefault', 'exclusive' + ]), + defaultSetting: r.uint8, + nameIndex: r.int16, + name: t => t.parent.parent.name.records.fontFeatures[t.nameIndex] +}); + +export default new r.Struct({ + version: r.fixed32, + featureNameCount: r.uint16, + reserved1: new r.Reserved(r.uint16), + reserved2: new r.Reserved(r.uint32), + featureNames: new r.Array(FeatureName, 'featureNameCount') +}); diff --git a/node_modules/fontkit/src/tables/fpgm.js b/node_modules/fontkit/src/tables/fpgm.js new file mode 100644 index 0000000000000000000000000000000000000000..fde3e4df474fbb72692bdcaa73e7241b779e9d7d --- /dev/null +++ b/node_modules/fontkit/src/tables/fpgm.js @@ -0,0 +1,8 @@ +import * as r from 'restructure'; + +// A list of instructions that are executed once when a font is first used. +// These instructions are known as the font program. The main use of this table +// is for the definition of functions that are used in many different glyph programs. +export default new r.Struct({ + instructions: new r.Array(r.uint8) +}); diff --git a/node_modules/fontkit/src/tables/fvar.js b/node_modules/fontkit/src/tables/fvar.js new file mode 100644 index 0000000000000000000000000000000000000000..d4187ed46050c68840d9947c13141aff57bcb7a3 --- /dev/null +++ b/node_modules/fontkit/src/tables/fvar.js @@ -0,0 +1,31 @@ +import * as r from 'restructure'; + +let Axis = new r.Struct({ + axisTag: new r.String(4), + minValue: r.fixed32, + defaultValue: r.fixed32, + maxValue: r.fixed32, + flags: r.uint16, + nameID: r.uint16, + name: t => t.parent.parent.name.records.fontFeatures[t.nameID] +}); + +let Instance = new r.Struct({ + nameID: r.uint16, + name: t => t.parent.parent.name.records.fontFeatures[t.nameID], + flags: r.uint16, + coord: new r.Array(r.fixed32, t => t.parent.axisCount), + postscriptNameID: new r.Optional(r.uint16, t => t.parent.instanceSize - t._currentOffset > 0) +}); + +export default new r.Struct({ + version: r.fixed32, + offsetToData: r.uint16, + countSizePairs: r.uint16, + axisCount: r.uint16, + axisSize: r.uint16, + instanceCount: r.uint16, + instanceSize: r.uint16, + axis: new r.Array(Axis, 'axisCount'), + instance: new r.Array(Instance, 'instanceCount') +}); diff --git a/node_modules/fontkit/src/tables/gasp.js b/node_modules/fontkit/src/tables/gasp.js new file mode 100644 index 0000000000000000000000000000000000000000..d0925b2365391a7f343ddd21aa5288cf6b9a1124 --- /dev/null +++ b/node_modules/fontkit/src/tables/gasp.js @@ -0,0 +1,15 @@ +import * as r from 'restructure'; + +let GaspRange = new r.Struct({ + rangeMaxPPEM: r.uint16, // Upper limit of range, in ppem + rangeGaspBehavior: new r.Bitfield(r.uint16, [ // Flags describing desired rasterizer behavior + 'grayscale', 'gridfit', + 'symmetricSmoothing', 'symmetricGridfit' // only in version 1, for ClearType + ]) +}); + +export default new r.Struct({ + version: r.uint16, // set to 0 + numRanges: r.uint16, + gaspRanges: new r.Array(GaspRange, 'numRanges') // Sorted by ppem +}); diff --git a/node_modules/fontkit/src/tables/glyf.js b/node_modules/fontkit/src/tables/glyf.js new file mode 100644 index 0000000000000000000000000000000000000000..207bb3ca04017e1143fec2acb6af20e2e1ec7e3b --- /dev/null +++ b/node_modules/fontkit/src/tables/glyf.js @@ -0,0 +1,4 @@ +import * as r from 'restructure'; + +// only used for encoding +export default new r.Array(new r.Buffer); diff --git a/node_modules/fontkit/src/tables/gvar.js b/node_modules/fontkit/src/tables/gvar.js new file mode 100644 index 0000000000000000000000000000000000000000..8b4b1a48c9b6ba0e695e786a59fa12b46a20085d --- /dev/null +++ b/node_modules/fontkit/src/tables/gvar.js @@ -0,0 +1,27 @@ +import * as r from 'restructure'; + +let shortFrac = new r.Fixed(16, 'BE', 14); +class Offset { + static decode(stream, parent) { + // In short format, offsets are multiplied by 2. + // This doesn't seem to be documented by Apple, but it + // is implemented this way in Freetype. + return parent.flags + ? stream.readUInt32BE() + : stream.readUInt16BE() * 2; + } +} + +let gvar = new r.Struct({ + version: r.uint16, + reserved: new r.Reserved(r.uint16), + axisCount: r.uint16, + globalCoordCount: r.uint16, + globalCoords: new r.Pointer(r.uint32, new r.Array(new r.Array(shortFrac, 'axisCount'), 'globalCoordCount')), + glyphCount: r.uint16, + flags: r.uint16, + offsetToData: r.uint32, + offsets: new r.Array(new r.Pointer(Offset, 'void', { relativeTo: ctx => ctx.offsetToData, allowNull: false }), t => t.glyphCount + 1) +}); + +export default gvar; diff --git a/node_modules/fontkit/src/tables/hdmx.js b/node_modules/fontkit/src/tables/hdmx.js new file mode 100644 index 0000000000000000000000000000000000000000..511f089bd65eaaf412f8fb1cd86b1384f57879ce --- /dev/null +++ b/node_modules/fontkit/src/tables/hdmx.js @@ -0,0 +1,15 @@ +import * as r from 'restructure'; + +let DeviceRecord = new r.Struct({ + pixelSize: r.uint8, + maximumWidth: r.uint8, + widths: new r.Array(r.uint8, t => t.parent.parent.maxp.numGlyphs) +}); + +// The Horizontal Device Metrics table stores integer advance widths scaled to particular pixel sizes +export default new r.Struct({ + version: r.uint16, + numRecords: r.int16, + sizeDeviceRecord: r.int32, + records: new r.Array(DeviceRecord, 'numRecords') +}); diff --git a/node_modules/fontkit/src/tables/head.js b/node_modules/fontkit/src/tables/head.js new file mode 100644 index 0000000000000000000000000000000000000000..88f7a51bb236ce9181ee357d35d44df182711dd3 --- /dev/null +++ b/node_modules/fontkit/src/tables/head.js @@ -0,0 +1,25 @@ +import * as r from 'restructure'; + +// font header +export default new r.Struct({ + version: r.int32, // 0x00010000 (version 1.0) + revision: r.int32, // set by font manufacturer + checkSumAdjustment: r.uint32, + magicNumber: r.uint32, // set to 0x5F0F3CF5 + flags: r.uint16, + unitsPerEm: r.uint16, // range from 64 to 16384 + created: new r.Array(r.int32, 2), + modified: new r.Array(r.int32, 2), + xMin: r.int16, // for all glyph bounding boxes + yMin: r.int16, // for all glyph bounding boxes + xMax: r.int16, // for all glyph bounding boxes + yMax: r.int16, // for all glyph bounding boxes + macStyle: new r.Bitfield(r.uint16, [ + 'bold', 'italic', 'underline', 'outline', + 'shadow', 'condensed', 'extended' + ]), + lowestRecPPEM: r.uint16, // smallest readable size in pixels + fontDirectionHint: r.int16, + indexToLocFormat: r.int16, // 0 for short offsets, 1 for long + glyphDataFormat: r.int16 // 0 for current format +}); diff --git a/node_modules/fontkit/src/tables/hhea.js b/node_modules/fontkit/src/tables/hhea.js new file mode 100644 index 0000000000000000000000000000000000000000..af47604e5044c61c24ad56ce9aeb35618dbde92c --- /dev/null +++ b/node_modules/fontkit/src/tables/hhea.js @@ -0,0 +1,19 @@ +import * as r from 'restructure'; + +// horizontal header +export default new r.Struct({ + version: r.int32, + ascent: r.int16, // Distance from baseline of highest ascender + descent: r.int16, // Distance from baseline of lowest descender + lineGap: r.int16, // Typographic line gap + advanceWidthMax: r.uint16, // Maximum advance width value in 'hmtx' table + minLeftSideBearing: r.int16, // Maximum advance width value in 'hmtx' table + minRightSideBearing: r.int16, // Minimum right sidebearing value + xMaxExtent: r.int16, + caretSlopeRise: r.int16, // Used to calculate the slope of the cursor (rise/run); 1 for vertical + caretSlopeRun: r.int16, // 0 for vertical + caretOffset: r.int16, // Set to 0 for non-slanted fonts + reserved: new r.Reserved(r.int16, 4), + metricDataFormat: r.int16, // 0 for current format + numberOfMetrics: r.uint16 // Number of advance widths in 'hmtx' table +}); diff --git a/node_modules/fontkit/src/tables/hmtx.js b/node_modules/fontkit/src/tables/hmtx.js new file mode 100644 index 0000000000000000000000000000000000000000..6df2ae52e00b1b7cd80ee0ec5868325a59567336 --- /dev/null +++ b/node_modules/fontkit/src/tables/hmtx.js @@ -0,0 +1,11 @@ +import * as r from 'restructure'; + +let HmtxEntry = new r.Struct({ + advance: r.uint16, + bearing: r.int16 +}); + +export default new r.Struct({ + metrics: new r.LazyArray(HmtxEntry, t => t.parent.hhea.numberOfMetrics), + bearings: new r.LazyArray(r.int16, t => t.parent.maxp.numGlyphs - t.parent.hhea.numberOfMetrics) +}); diff --git a/node_modules/fontkit/src/tables/index.js b/node_modules/fontkit/src/tables/index.js new file mode 100644 index 0000000000000000000000000000000000000000..438bb48c44a37d604f0aa4059448f4e611a8789b --- /dev/null +++ b/node_modules/fontkit/src/tables/index.js @@ -0,0 +1,117 @@ +let tables = {}; +export default tables; + +// Required Tables +import cmap from './cmap'; +import head from './head'; +import hhea from './hhea'; +import hmtx from './hmtx'; +import maxp from './maxp'; +import name from './name'; +import OS2 from './OS2'; +import post from './post'; + +tables.cmap = cmap; +tables.head = head; +tables.hhea = hhea; +tables.hmtx = hmtx; +tables.maxp = maxp; +tables.name = name; +tables['OS/2'] = OS2; +tables.post = post; + + +// TrueType Outlines +import cvt from './cvt'; +import fpgm from './fpgm'; +import loca from './loca'; +import prep from './prep'; +import glyf from './glyf'; + +tables.fpgm = fpgm; +tables.loca = loca; +tables.prep = prep; +tables['cvt '] = cvt; +tables.glyf = glyf; + + +// PostScript Outlines +import CFFFont from '../cff/CFFFont'; +import VORG from './VORG'; + +tables['CFF '] = CFFFont; +tables['CFF2'] = CFFFont; +tables.VORG = VORG; + + +// Bitmap Glyphs +import EBLC from './EBLC'; +import sbix from './sbix'; +import COLR from './COLR'; +import CPAL from './CPAL'; + +tables.EBLC = EBLC; +tables.CBLC = tables.EBLC; +tables.sbix = sbix; +tables.COLR = COLR; +tables.CPAL = CPAL; + + +// Advanced OpenType Tables +import BASE from './BASE'; +import GDEF from './GDEF'; +import GPOS from './GPOS'; +import GSUB from './GSUB'; +import JSTF from './JSTF'; + +tables.BASE = BASE; +tables.GDEF = GDEF; +tables.GPOS = GPOS; +tables.GSUB = GSUB; +tables.JSTF = JSTF; + +// OpenType variations tables +import HVAR from './HVAR'; + +tables.HVAR = HVAR; + +// Other OpenType Tables +import DSIG from './DSIG'; +import gasp from './gasp'; +import hdmx from './hdmx'; +import kern from './kern'; +import LTSH from './LTSH'; +import PCLT from './PCLT'; +import VDMX from './VDMX'; +import vhea from './vhea'; +import vmtx from './vmtx'; + +tables.DSIG = DSIG; +tables.gasp = gasp; +tables.hdmx = hdmx; +tables.kern = kern; +tables.LTSH = LTSH; +tables.PCLT = PCLT; +tables.VDMX = VDMX; +tables.vhea = vhea; +tables.vmtx = vmtx; + + +// Apple Advanced Typography Tables +import avar from './avar'; +import bsln from './bsln'; +import feat from './feat'; +import fvar from './fvar'; +import gvar from './gvar'; +import just from './just'; +import morx from './morx'; +import opbd from './opbd'; + +tables.avar = avar; +tables.bsln = bsln; +tables.feat = feat; +tables.fvar = fvar; +tables.gvar = gvar; +tables.just = just; +tables.morx = morx; +tables.opbd = opbd; diff --git a/node_modules/fontkit/src/tables/just.js b/node_modules/fontkit/src/tables/just.js new file mode 100644 index 0000000000000000000000000000000000000000..198be1bfe9fec0e039624ec2947ee242990374cf --- /dev/null +++ b/node_modules/fontkit/src/tables/just.js @@ -0,0 +1,81 @@ +import * as r from 'restructure'; +import { LookupTable, StateTable1 } from './aat'; + +let ClassTable = new r.Struct({ + length: r.uint16, + coverage: r.uint16, + subFeatureFlags: r.uint32, + stateTable: new StateTable1 +}); + +let WidthDeltaRecord = new r.Struct({ + justClass: r.uint32, + beforeGrowLimit: r.fixed32, + beforeShrinkLimit: r.fixed32, + afterGrowLimit: r.fixed32, + afterShrinkLimit: r.fixed32, + growFlags: r.uint16, + shrinkFlags: r.uint16 +}); + +let WidthDeltaCluster = new r.Array(WidthDeltaRecord, r.uint32); + +let ActionData = new r.VersionedStruct('actionType', { + 0: { // Decomposition action + lowerLimit: r.fixed32, + upperLimit: r.fixed32, + order: r.uint16, + glyphs: new r.Array(r.uint16, r.uint16) + }, + + 1: { // Unconditional add glyph action + addGlyph: r.uint16 + }, + + 2: { // Conditional add glyph action + substThreshold: r.fixed32, + addGlyph: r.uint16, + substGlyph: r.uint16 + }, + + 3: {}, // Stretch glyph action (no data, not supported by CoreText) + + 4: { // Ductile glyph action (not supported by CoreText) + variationAxis: r.uint32, + minimumLimit: r.fixed32, + noStretchValue: r.fixed32, + maximumLimit: r.fixed32 + }, + + 5: { // Repeated add glyph action + flags: r.uint16, + glyph: r.uint16 + } +}); + +let Action = new r.Struct({ + actionClass: r.uint16, + actionType: r.uint16, + actionLength: r.uint32, + actionData: ActionData, + padding: new r.Reserved(r.uint8, t => t.actionLength - t._currentOffset) +}); + +let PostcompensationAction = new r.Array(Action, r.uint32); +let PostCompensationTable = new r.Struct({ + lookupTable: new LookupTable(new r.Pointer(r.uint16, PostcompensationAction)) +}); + +let JustificationTable = new r.Struct({ + classTable: new r.Pointer(r.uint16, ClassTable, { type: 'parent' }), + wdcOffset: r.uint16, + postCompensationTable: new r.Pointer(r.uint16, PostCompensationTable, { type: 'parent' }), + widthDeltaClusters: new LookupTable(new r.Pointer(r.uint16, WidthDeltaCluster, { type: 'parent', relativeTo: ctx => ctx.wdcOffset })) +}); + +export default new r.Struct({ + version: r.uint32, + format: r.uint16, + horizontal: new r.Pointer(r.uint16, JustificationTable), + vertical: new r.Pointer(r.uint16, JustificationTable) +}); diff --git a/node_modules/fontkit/src/tables/kern.js b/node_modules/fontkit/src/tables/kern.js new file mode 100644 index 0000000000000000000000000000000000000000..9ce4d9020b64d07cd2de698add3e6d31c145c731 --- /dev/null +++ b/node_modules/fontkit/src/tables/kern.js @@ -0,0 +1,91 @@ +import * as r from 'restructure'; + +let KernPair = new r.Struct({ + left: r.uint16, + right: r.uint16, + value: r.int16 +}); + +let ClassTable = new r.Struct({ + firstGlyph: r.uint16, + nGlyphs: r.uint16, + offsets: new r.Array(r.uint16, 'nGlyphs'), + max: t => t.offsets.length && Math.max.apply(Math, t.offsets) +}); + +let Kern2Array = new r.Struct({ + off: t => t._startOffset - t.parent.parent._startOffset, + len: t => (((t.parent.leftTable.max - t.off) / t.parent.rowWidth) + 1) * (t.parent.rowWidth / 2), + values: new r.LazyArray(r.int16, 'len') +}); + +let KernSubtable = new r.VersionedStruct('format', { + 0: { + nPairs: r.uint16, + searchRange: r.uint16, + entrySelector: r.uint16, + rangeShift: r.uint16, + pairs: new r.Array(KernPair, 'nPairs') + }, + + 2: { + rowWidth: r.uint16, + leftTable: new r.Pointer(r.uint16, ClassTable, {type: 'parent'}), + rightTable: new r.Pointer(r.uint16, ClassTable, {type: 'parent'}), + array: new r.Pointer(r.uint16, Kern2Array, {type: 'parent'}) + }, + + 3: { + glyphCount: r.uint16, + kernValueCount: r.uint8, + leftClassCount: r.uint8, + rightClassCount: r.uint8, + flags: r.uint8, + kernValue: new r.Array(r.int16, 'kernValueCount'), + leftClass: new r.Array(r.uint8, 'glyphCount'), + rightClass: new r.Array(r.uint8, 'glyphCount'), + kernIndex: new r.Array(r.uint8, t => t.leftClassCount * t.rightClassCount) + } +}); + +let KernTable = new r.VersionedStruct('version', { + 0: { // Microsoft uses this format + subVersion: r.uint16, // Microsoft has an extra sub-table version number + length: r.uint16, // Length of the subtable, in bytes + format: r.uint8, // Format of subtable + coverage: new r.Bitfield(r.uint8, [ + 'horizontal', // 1 if table has horizontal data, 0 if vertical + 'minimum', // If set to 1, the table has minimum values. If set to 0, the table has kerning values. + 'crossStream', // If set to 1, kerning is perpendicular to the flow of the text + 'override' // If set to 1 the value in this table replaces the accumulated value + ]), + subtable: KernSubtable, + padding: new r.Reserved(r.uint8, t => t.length - t._currentOffset) + }, + 1: { // Apple uses this format + length: r.uint32, + coverage: new r.Bitfield(r.uint8, [ + null, null, null, null, null, + 'variation', // Set if table has variation kerning values + 'crossStream', // Set if table has cross-stream kerning values + 'vertical' // Set if table has vertical kerning values + ]), + format: r.uint8, + tupleIndex: r.uint16, + subtable: KernSubtable, + padding: new r.Reserved(r.uint8, t => t.length - t._currentOffset) + } +}); + +export default new r.VersionedStruct(r.uint16, { + 0: { // Microsoft Version + nTables: r.uint16, + tables: new r.Array(KernTable, 'nTables') + }, + + 1: { // Apple Version + reserved: new r.Reserved(r.uint16), // the other half of the version number + nTables: r.uint32, + tables: new r.Array(KernTable, 'nTables') + } +}); diff --git a/node_modules/fontkit/src/tables/loca.js b/node_modules/fontkit/src/tables/loca.js new file mode 100644 index 0000000000000000000000000000000000000000..8d1ea6a20749fee160d62f7a98c32d8c9e17f2a7 --- /dev/null +++ b/node_modules/fontkit/src/tables/loca.js @@ -0,0 +1,30 @@ +import * as r from 'restructure'; + +let loca = new r.VersionedStruct('head.indexToLocFormat', { + 0: { + offsets: new r.Array(r.uint16) + }, + 1: { + offsets: new r.Array(r.uint32) + } +}); + +loca.process = function() { + if (this.version === 0 && !this._processed) { + for (let i = 0; i < this.offsets.length; i++) { + this.offsets[i] <<= 1; + } + this._processed = true; + } +}; + +loca.preEncode = function() { + if (this.version === 0 && this._processed !== false) { + for (let i = 0; i < this.offsets.length; i++) { + this.offsets[i] >>>= 1; + } + this._processed = false; + } +}; + +export default loca; diff --git a/node_modules/fontkit/src/tables/maxp.js b/node_modules/fontkit/src/tables/maxp.js new file mode 100644 index 0000000000000000000000000000000000000000..3e211388b48408849c1cc5793d27e73b3489e7df --- /dev/null +++ b/node_modules/fontkit/src/tables/maxp.js @@ -0,0 +1,20 @@ +import * as r from 'restructure'; + +// maxiumum profile +export default new r.Struct({ + version: r.int32, + numGlyphs: r.uint16, // The number of glyphs in the font + maxPoints: r.uint16, // Maximum points in a non-composite glyph + maxContours: r.uint16, // Maximum contours in a non-composite glyph + maxComponentPoints: r.uint16, // Maximum points in a composite glyph + maxComponentContours: r.uint16, // Maximum contours in a composite glyph + maxZones: r.uint16, // 1 if instructions do not use the twilight zone, 2 otherwise + maxTwilightPoints: r.uint16, // Maximum points used in Z0 + maxStorage: r.uint16, // Number of Storage Area locations + maxFunctionDefs: r.uint16, // Number of FDEFs + maxInstructionDefs: r.uint16, // Number of IDEFs + maxStackElements: r.uint16, // Maximum stack depth + maxSizeOfInstructions: r.uint16, // Maximum byte count for glyph instructions + maxComponentElements: r.uint16, // Maximum number of components referenced at “top level” for any composite glyph + maxComponentDepth: r.uint16 // Maximum levels of recursion; 1 for simple components +}); diff --git a/node_modules/fontkit/src/tables/morx.js b/node_modules/fontkit/src/tables/morx.js new file mode 100644 index 0000000000000000000000000000000000000000..73bc296244957261ac46256f082c706348bbfd57 --- /dev/null +++ b/node_modules/fontkit/src/tables/morx.js @@ -0,0 +1,79 @@ +import * as r from 'restructure'; +import { UnboundedArray, LookupTable, StateTable } from './aat'; + +let LigatureData = { + action: r.uint16 +}; + +let ContextualData = { + markIndex: r.uint16, + currentIndex: r.uint16 +}; + +let InsertionData = { + currentInsertIndex: r.uint16, + markedInsertIndex: r.uint16 +}; + +let SubstitutionTable = new r.Struct({ + items: new UnboundedArray(new r.Pointer(r.uint32, new LookupTable)) +}); + +let SubtableData = new r.VersionedStruct('type', { + 0: { // Indic Rearrangement Subtable + stateTable: new StateTable + }, + + 1: { // Contextual Glyph Substitution Subtable + stateTable: new StateTable(ContextualData), + substitutionTable: new r.Pointer(r.uint32, SubstitutionTable) + }, + + 2: { // Ligature subtable + stateTable: new StateTable(LigatureData), + ligatureActions: new r.Pointer(r.uint32, new UnboundedArray(r.uint32)), + components: new r.Pointer(r.uint32, new UnboundedArray(r.uint16)), + ligatureList: new r.Pointer(r.uint32, new UnboundedArray(r.uint16)) + }, + + 4: { // Non-contextual Glyph Substitution Subtable + lookupTable: new LookupTable + }, + + 5: { // Glyph Insertion Subtable + stateTable: new StateTable(InsertionData), + insertionActions: new r.Pointer(r.uint32, new UnboundedArray(r.uint16)) + } +}); + +let Subtable = new r.Struct({ + length: r.uint32, + coverage: r.uint24, + type: r.uint8, + subFeatureFlags: r.uint32, + table: SubtableData, + padding: new r.Reserved(r.uint8, t => t.length - t._currentOffset) +}); + +let FeatureEntry = new r.Struct({ + featureType: r.uint16, + featureSetting: r.uint16, + enableFlags: r.uint32, + disableFlags: r.uint32 +}); + +let MorxChain = new r.Struct({ + defaultFlags: r.uint32, + chainLength: r.uint32, + nFeatureEntries: r.uint32, + nSubtables: r.uint32, + features: new r.Array(FeatureEntry, 'nFeatureEntries'), + subtables: new r.Array(Subtable, 'nSubtables') +}); + +export default new r.Struct({ + version: r.uint16, + unused: new r.Reserved(r.uint16), + nChains: r.uint32, + chains: new r.Array(MorxChain, 'nChains') +}); diff --git a/node_modules/fontkit/src/tables/name.js b/node_modules/fontkit/src/tables/name.js new file mode 100644 index 0000000000000000000000000000000000000000..c5542d2268508811a4b2335b16c1fea1400d1a16 --- /dev/null +++ b/node_modules/fontkit/src/tables/name.js @@ -0,0 +1,130 @@ +import * as r from 'restructure'; +import {getEncoding, LANGUAGES} from '../encodings'; + +let NameRecord = new r.Struct({ + platformID: r.uint16, + encodingID: r.uint16, + languageID: r.uint16, + nameID: r.uint16, + length: r.uint16, + string: new r.Pointer(r.uint16, + new r.String('length', t => getEncoding(t.platformID, t.encodingID, t.languageID)), + { type: 'parent', relativeTo: ctx => ctx.parent.stringOffset, allowNull: false } + ) +}); + +let LangTagRecord = new r.Struct({ + length: r.uint16, + tag: new r.Pointer(r.uint16, new r.String('length', 'utf16be'), {type: 'parent', relativeTo: ctx => ctx.stringOffset}) +}); + +var NameTable = new r.VersionedStruct(r.uint16, { + 0: { + count: r.uint16, + stringOffset: r.uint16, + records: new r.Array(NameRecord, 'count') + }, + 1: { + count: r.uint16, + stringOffset: r.uint16, + records: new r.Array(NameRecord, 'count'), + langTagCount: r.uint16, + langTags: new r.Array(LangTagRecord, 'langTagCount') + } +}); + +export default NameTable; + +const NAMES = [ + 'copyright', + 'fontFamily', + 'fontSubfamily', + 'uniqueSubfamily', + 'fullName', + 'version', + 'postscriptName', // Note: A font may have only one PostScript name and that name must be ASCII. + 'trademark', + 'manufacturer', + 'designer', + 'description', + 'vendorURL', + 'designerURL', + 'license', + 'licenseURL', + null, // reserved + 'preferredFamily', + 'preferredSubfamily', + 'compatibleFull', + 'sampleText', + 'postscriptCIDFontName', + 'wwsFamilyName', + 'wwsSubfamilyName' +]; + +NameTable.process = function(stream) { + var records = {}; + for (let record of this.records) { + // find out what language this is for + let language = LANGUAGES[record.platformID][record.languageID]; + + if (language == null && this.langTags != null && record.languageID >= 0x8000) { + language = this.langTags[record.languageID - 0x8000].tag; + } + + if (language == null) { + language = record.platformID + '-' + record.languageID; + } + + // if the nameID is >= 256, it is a font feature record (AAT) + let key = record.nameID >= 256 ? 'fontFeatures' : (NAMES[record.nameID] || record.nameID); + if (records[key] == null) { + records[key] = {}; + } + + let obj = records[key]; + if (record.nameID >= 256) { + obj = obj[record.nameID] || (obj[record.nameID] = {}); + } + + if (typeof record.string === 'string' || typeof obj[language] !== 'string') { + obj[language] = record.string; + } + } + + this.records = records; +}; + +NameTable.preEncode = function() { + if (Array.isArray(this.records)) return; + this.version = 0; + + let records = []; + for (let key in this.records) { + let val = this.records[key]; + if (key === 'fontFeatures') continue; + + records.push({ + platformID: 3, + encodingID: 1, + languageID: 0x409, + nameID: NAMES.indexOf(key), + length: val.en.length * 2, + string: val.en + }); + + if (key === 'postscriptName') { + records.push({ + platformID: 1, + encodingID: 0, + languageID: 0, + nameID: NAMES.indexOf(key), + length: val.en.length, + string: val.en + }); + } + } + + this.records = records; + this.count = records.length; + this.stringOffset = NameTable.size(this, null, false); +}; diff --git a/node_modules/fontkit/src/tables/opbd.js b/node_modules/fontkit/src/tables/opbd.js new file mode 100644 index 0000000000000000000000000000000000000000..7c614f21bf70a2c9dff68020ea276cbcd84f394f --- /dev/null +++ b/node_modules/fontkit/src/tables/opbd.js @@ -0,0 +1,15 @@ +import * as r from 'restructure'; +import { LookupTable } from './aat'; + +let OpticalBounds = new r.Struct({ + left: r.int16, + top: r.int16, + right: r.int16, + bottom: r.int16 +}); + +export default new r.Struct({ + version: r.fixed32, + format: r.uint16, + lookupTable: new LookupTable(OpticalBounds) +}); diff --git a/node_modules/fontkit/src/tables/opentype.js b/node_modules/fontkit/src/tables/opentype.js new file mode 100644 index 0000000000000000000000000000000000000000..867cf5cb0b7b9ebc853d76a618adc14b4b55e39b --- /dev/null +++ b/node_modules/fontkit/src/tables/opentype.js @@ -0,0 +1,217 @@ +import * as r from 'restructure'; + +//######################## +// Scripts and Languages # +//######################## + +let LangSysTable = new r.Struct({ + reserved: new r.Reserved(r.uint16), + reqFeatureIndex: r.uint16, + featureCount: r.uint16, + featureIndexes: new r.Array(r.uint16, 'featureCount') +}); + +let LangSysRecord = new r.Struct({ + tag: new r.String(4), + langSys: new r.Pointer(r.uint16, LangSysTable, { type: 'parent' }) +}); + +let Script = new r.Struct({ + defaultLangSys: new r.Pointer(r.uint16, LangSysTable), + count: r.uint16, + langSysRecords: new r.Array(LangSysRecord, 'count') +}); + +let ScriptRecord = new r.Struct({ + tag: new r.String(4), + script: new r.Pointer(r.uint16, Script, { type: 'parent' }) +}); + +export let ScriptList = new r.Array(ScriptRecord, r.uint16); + +//####################### +// Features and Lookups # +//####################### + +let FeatureParams = new r.Struct({ + version: r.uint16, // should be set to 0 according OT spec + nameID: r.uint16, //OT spec: UI Name ID or uiLabelNameId +}); + +export let Feature = new r.Struct({ + featureParams: new r.Pointer(r.uint16, FeatureParams), + lookupCount: r.uint16, + lookupListIndexes: new r.Array(r.uint16, 'lookupCount') +}); + +let FeatureRecord = new r.Struct({ + tag: new r.String(4), + feature: new r.Pointer(r.uint16, Feature, { type: 'parent' }) +}); + +export let FeatureList = new r.Array(FeatureRecord, r.uint16); + +let LookupFlags = new r.Struct({ + markAttachmentType: r.uint8, + flags: new r.Bitfield(r.uint8, [ + 'rightToLeft', 'ignoreBaseGlyphs', 'ignoreLigatures', + 'ignoreMarks', 'useMarkFilteringSet' + ]) +}); + +export function LookupList(SubTable) { + let Lookup = new r.Struct({ + lookupType: r.uint16, + flags: LookupFlags, + subTableCount: r.uint16, + subTables: new r.Array(new r.Pointer(r.uint16, SubTable), 'subTableCount'), + markFilteringSet: new r.Optional(r.uint16, t => t.flags.flags.useMarkFilteringSet) + }); + + return new r.LazyArray(new r.Pointer(r.uint16, Lookup), r.uint16); +} + +//################# +// Coverage Table # +//################# + +let RangeRecord = new r.Struct({ + start: r.uint16, + end: r.uint16, + startCoverageIndex: r.uint16 +}); + +export let Coverage = new r.VersionedStruct(r.uint16, { + 1: { + glyphCount: r.uint16, + glyphs: new r.Array(r.uint16, 'glyphCount') + }, + 2: { + rangeCount: r.uint16, + rangeRecords: new r.Array(RangeRecord, 'rangeCount') + } +}); + +//######################### +// Class Definition Table # +//######################### + +let ClassRangeRecord = new r.Struct({ + start: r.uint16, + end: r.uint16, + class: r.uint16 +}); + +export let ClassDef = new r.VersionedStruct(r.uint16, { + 1: { // Class array + startGlyph: r.uint16, + glyphCount: r.uint16, + classValueArray: new r.Array(r.uint16, 'glyphCount') + }, + 2: { // Class ranges + classRangeCount: r.uint16, + classRangeRecord: new r.Array(ClassRangeRecord, 'classRangeCount') + } +}); + +//############### +// Device Table # +//############### + +export let Device = new r.Struct({ + a: r.uint16, // startSize for hinting Device, outerIndex for VariationIndex + b: r.uint16, // endSize for Device, innerIndex for VariationIndex + deltaFormat: r.uint16 +}); + +//############################################# +// Contextual Substitution/Positioning Tables # +//############################################# + +let LookupRecord = new r.Struct({ + sequenceIndex: r.uint16, + lookupListIndex: r.uint16 +}); + +let Rule = new r.Struct({ + glyphCount: r.uint16, + lookupCount: r.uint16, + input: new r.Array(r.uint16, t => t.glyphCount - 1), + lookupRecords: new r.Array(LookupRecord, 'lookupCount') +}); + +let RuleSet = new r.Array(new r.Pointer(r.uint16, Rule), r.uint16); + +let ClassRule = new r.Struct({ + glyphCount: r.uint16, + lookupCount: r.uint16, + classes: new r.Array(r.uint16, t => t.glyphCount - 1), + lookupRecords: new r.Array(LookupRecord, 'lookupCount') +}); + +let ClassSet = new r.Array(new r.Pointer(r.uint16, ClassRule), r.uint16); + +export let Context = new r.VersionedStruct(r.uint16, { + 1: { // Simple context + coverage: new r.Pointer(r.uint16, Coverage), + ruleSetCount: r.uint16, + ruleSets: new r.Array(new r.Pointer(r.uint16, RuleSet), 'ruleSetCount') + }, + 2: { // Class-based context + coverage: new r.Pointer(r.uint16, Coverage), + classDef: new r.Pointer(r.uint16, ClassDef), + classSetCnt: r.uint16, + classSet: new r.Array(new r.Pointer(r.uint16, ClassSet), 'classSetCnt') + }, + 3: { + glyphCount: r.uint16, + lookupCount: r.uint16, + coverages: new r.Array(new r.Pointer(r.uint16, Coverage), 'glyphCount'), + lookupRecords: new r.Array(LookupRecord, 'lookupCount') + } +}); + +//###################################################### +// Chaining Contextual Substitution/Positioning Tables # +//###################################################### + +let ChainRule = new r.Struct({ + backtrackGlyphCount: r.uint16, + backtrack: new r.Array(r.uint16, 'backtrackGlyphCount'), + inputGlyphCount: r.uint16, + input: new r.Array(r.uint16, t => t.inputGlyphCount - 1), + lookaheadGlyphCount: r.uint16, + lookahead: new r.Array(r.uint16, 'lookaheadGlyphCount'), + lookupCount: r.uint16, + lookupRecords: new r.Array(LookupRecord, 'lookupCount') +}); + +let ChainRuleSet = new r.Array(new r.Pointer(r.uint16, ChainRule), r.uint16); + +export let ChainingContext = new r.VersionedStruct(r.uint16, { + 1: { // Simple context glyph substitution + coverage: new r.Pointer(r.uint16, Coverage), + chainCount: r.uint16, + chainRuleSets: new r.Array(new r.Pointer(r.uint16, ChainRuleSet), 'chainCount') + }, + + 2: { // Class-based chaining context + coverage: new r.Pointer(r.uint16, Coverage), + backtrackClassDef: new r.Pointer(r.uint16, ClassDef), + inputClassDef: new r.Pointer(r.uint16, ClassDef), + lookaheadClassDef: new r.Pointer(r.uint16, ClassDef), + chainCount: r.uint16, + chainClassSet: new r.Array(new r.Pointer(r.uint16, ChainRuleSet), 'chainCount') + }, + + 3: { // Coverage-based chaining context + backtrackGlyphCount: r.uint16, + backtrackCoverage: new r.Array(new r.Pointer(r.uint16, Coverage), 'backtrackGlyphCount'), + inputGlyphCount: r.uint16, + inputCoverage: new r.Array(new r.Pointer(r.uint16, Coverage), 'inputGlyphCount'), + lookaheadGlyphCount: r.uint16, + lookaheadCoverage: new r.Array(new r.Pointer(r.uint16, Coverage), 'lookaheadGlyphCount'), + lookupCount: r.uint16, + lookupRecords: new r.Array(LookupRecord, 'lookupCount') + } +}); diff --git a/node_modules/fontkit/src/tables/post.js b/node_modules/fontkit/src/tables/post.js new file mode 100644 index 0000000000000000000000000000000000000000..04fdeabeb9d8f47cafcb61fb51a786adf238f0d1 --- /dev/null +++ b/node_modules/fontkit/src/tables/post.js @@ -0,0 +1,34 @@ +import * as r from 'restructure'; + +// PostScript information +export default new r.VersionedStruct(r.fixed32, { + header: { // these fields exist at the top of all versions + italicAngle: r.fixed32, // Italic angle in counter-clockwise degrees from the vertical. + underlinePosition: r.int16, // Suggested distance of the top of the underline from the baseline + underlineThickness: r.int16, // Suggested values for the underline thickness + isFixedPitch: r.uint32, // Whether the font is monospaced + minMemType42: r.uint32, // Minimum memory usage when a TrueType font is downloaded as a Type 42 font + maxMemType42: r.uint32, // Maximum memory usage when a TrueType font is downloaded as a Type 42 font + minMemType1: r.uint32, // Minimum memory usage when a TrueType font is downloaded as a Type 1 font + maxMemType1: r.uint32 // Maximum memory usage when a TrueType font is downloaded as a Type 1 font + }, + + 1: {}, // version 1 has no additional fields + + 2: { + numberOfGlyphs: r.uint16, + glyphNameIndex: new r.Array(r.uint16, 'numberOfGlyphs'), + names: new r.Array(new r.String(r.uint8)) + }, + + 2.5: { + numberOfGlyphs: r.uint16, + offsets: new r.Array(r.uint8, 'numberOfGlyphs') + }, + + 3: {}, // version 3 has no additional fields + + 4: { + map: new r.Array(r.uint32, t => t.parent.maxp.numGlyphs) + } +}); diff --git a/node_modules/fontkit/src/tables/prep.js b/node_modules/fontkit/src/tables/prep.js new file mode 100644 index 0000000000000000000000000000000000000000..4b784a5a759e6854628489e98cd96caa99fc9098 --- /dev/null +++ b/node_modules/fontkit/src/tables/prep.js @@ -0,0 +1,6 @@ +import * as r from 'restructure'; + +// Set of instructions executed whenever the point size or font transformation change +export default new r.Struct({ + controlValueProgram: new r.Array(r.uint8) +}); diff --git a/node_modules/fontkit/src/tables/sbix.js b/node_modules/fontkit/src/tables/sbix.js new file mode 100644 index 0000000000000000000000000000000000000000..140824c6de23813bad00f415f002c1263e457947 --- /dev/null +++ b/node_modules/fontkit/src/tables/sbix.js @@ -0,0 +1,17 @@ +import * as r from 'restructure'; + +let ImageTable = new r.Struct({ + ppem: r.uint16, + resolution: r.uint16, + imageOffsets: new r.Array(new r.Pointer(r.uint32, 'void'), t => t.parent.parent.maxp.numGlyphs + 1) +}); + +// This is the Apple sbix table, used by the "Apple Color Emoji" font. +// It includes several image tables with images for each bitmap glyph +// of several different sizes. +export default new r.Struct({ + version: r.uint16, + flags: new r.Bitfield(r.uint16, ['renderOutlines']), + numImgTables: r.uint32, + imageTables: new r.Array(new r.Pointer(r.uint32, ImageTable), 'numImgTables') +}); diff --git a/node_modules/fontkit/src/tables/variations.js b/node_modules/fontkit/src/tables/variations.js new file mode 100644 index 0000000000000000000000000000000000000000..0aae61c3c2748f1b822925e0f2fc7d6101932e20 --- /dev/null +++ b/node_modules/fontkit/src/tables/variations.js @@ -0,0 +1,81 @@ +import {Feature} from './opentype'; +import * as r from 'restructure'; + +/******************* + * Variation Store * + *******************/ + +let F2DOT14 = new r.Fixed(16, 'BE', 14); +let RegionAxisCoordinates = new r.Struct({ + startCoord: F2DOT14, + peakCoord: F2DOT14, + endCoord: F2DOT14 +}); + +let VariationRegionList = new r.Struct({ + axisCount: r.uint16, + regionCount: r.uint16, + variationRegions: new r.Array(new r.Array(RegionAxisCoordinates, 'axisCount'), 'regionCount') +}); + +let DeltaSet = new r.Struct({ + shortDeltas: new r.Array(r.int16, t => t.parent.shortDeltaCount), + regionDeltas: new r.Array(r.int8, t => t.parent.regionIndexCount - t.parent.shortDeltaCount), + deltas: t => t.shortDeltas.concat(t.regionDeltas) +}); + +let ItemVariationData = new r.Struct({ + itemCount: r.uint16, + shortDeltaCount: r.uint16, + regionIndexCount: r.uint16, + regionIndexes: new r.Array(r.uint16, 'regionIndexCount'), + deltaSets: new r.Array(DeltaSet, 'itemCount') +}); + +export let ItemVariationStore = new r.Struct({ + format: r.uint16, + variationRegionList: new r.Pointer(r.uint32, VariationRegionList), + variationDataCount: r.uint16, + itemVariationData: new r.Array(new r.Pointer(r.uint32, ItemVariationData), 'variationDataCount') +}); + +/********************** + * Feature Variations * + **********************/ + +let ConditionTable = new r.VersionedStruct(r.uint16, { + 1: { + axisIndex: r.uint16, + axisIndex: r.uint16, + filterRangeMinValue: F2DOT14, + filterRangeMaxValue: F2DOT14 + } +}); + +let ConditionSet = new r.Struct({ + conditionCount: r.uint16, + conditionTable: new r.Array(new r.Pointer(r.uint32, ConditionTable), 'conditionCount') +}); + +let FeatureTableSubstitutionRecord = new r.Struct({ + featureIndex: r.uint16, + alternateFeatureTable: new r.Pointer(r.uint32, Feature, {type: 'parent'}) +}); + +let FeatureTableSubstitution = new r.Struct({ + version: r.fixed32, + substitutionCount: r.uint16, + substitutions: new r.Array(FeatureTableSubstitutionRecord, 'substitutionCount') +}); + +let FeatureVariationRecord = new r.Struct({ + conditionSet: new r.Pointer(r.uint32, ConditionSet, {type: 'parent'}), + featureTableSubstitution: new r.Pointer(r.uint32, FeatureTableSubstitution, {type: 'parent'}) +}); + +export let FeatureVariations = new r.Struct({ + majorVersion: r.uint16, + minorVersion: r.uint16, + featureVariationRecordCount: r.uint32, + featureVariationRecords: new r.Array(FeatureVariationRecord, 'featureVariationRecordCount') +}); diff --git a/node_modules/fontkit/src/tables/vhea.js b/node_modules/fontkit/src/tables/vhea.js new file mode 100644 index 0000000000000000000000000000000000000000..004cdf93cd8b62db9b4d6166b6e65dbaa84cc742 --- /dev/null +++ b/node_modules/fontkit/src/tables/vhea.js @@ -0,0 +1,19 @@ +import * as r from 'restructure'; + +// Vertical Header Table +export default new r.Struct({ + version: r.uint16, // Version number of the Vertical Header Table + ascent: r.int16, // The vertical typographic ascender for this font + descent: r.int16, // The vertical typographic descender for this font + lineGap: r.int16, // The vertical typographic line gap for this font + advanceHeightMax: r.int16, // The maximum advance height measurement found in the font + minTopSideBearing: r.int16, // The minimum top side bearing measurement found in the font + minBottomSideBearing: r.int16, // The minimum bottom side bearing measurement found in the font + yMaxExtent: r.int16, + caretSlopeRise: r.int16, // Caret slope (rise/run) + caretSlopeRun: r.int16, + caretOffset: r.int16, // Set value equal to 0 for nonslanted fonts + reserved: new r.Reserved(r.int16, 4), + metricDataFormat: r.int16, // Set to 0 + numberOfMetrics: r.uint16 // Number of advance heights in the Vertical Metrics table +}); diff --git a/node_modules/fontkit/src/tables/vmtx.js b/node_modules/fontkit/src/tables/vmtx.js new file mode 100644 index 0000000000000000000000000000000000000000..579da6b7396ef61eeb69ea7192198fc982cb8c3e --- /dev/null +++ b/node_modules/fontkit/src/tables/vmtx.js @@ -0,0 +1,12 @@ +import * as r from 'restructure'; + +let VmtxEntry = new r.Struct({ + advance: r.uint16, // The advance height of the glyph + bearing: r.int16 // The top sidebearing of the glyph +}); + +// Vertical Metrics Table +export default new r.Struct({ + metrics: new r.LazyArray(VmtxEntry, t => t.parent.vhea.numberOfMetrics), + bearings: new r.LazyArray(r.int16, t => t.parent.maxp.numGlyphs - t.parent.vhea.numberOfMetrics) +}); diff --git a/node_modules/fontkit/src/utils.js b/node_modules/fontkit/src/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..72db57601ff3552f7194a24eac12ee8a2b821f20 --- /dev/null +++ b/node_modules/fontkit/src/utils.js @@ -0,0 +1,62 @@ +export function binarySearch(arr, cmp) { + let min = 0; + let max = arr.length - 1; + while (min <= max) { + let mid = (min + max) >> 1; + let res = cmp(arr[mid]); + + if (res < 0) { + max = mid - 1; + } else if (res > 0) { + min = mid + 1; + } else { + return mid; + } + } + + return -1; +} + +export function range(index, end) { + let range = []; + while (index < end) { + range.push(index++); + } + return range; +} + +export const asciiDecoder = new TextDecoder('ascii'); + +// Based on https://github.com/niklasvh/base64-arraybuffer. MIT license. +const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const LOOKUP = new Uint8Array(256); +for (let i = 0; i < CHARS.length; i++) { + LOOKUP[CHARS.charCodeAt(i)] = i; +} + +export function decodeBase64(base64) { + let bufferLength = base64.length * 0.75; + + if (base64[base64.length - 1] === '=') { + bufferLength--; + if (base64[base64.length - 2] === '=') { + bufferLength--; + } + } + + let bytes = new Uint8Array(bufferLength); + let p = 0; + + for (let i = 0, len = base64.length; i < len; i += 4) { + let encoded1 = LOOKUP[base64.charCodeAt(i)]; + let encoded2 = LOOKUP[base64.charCodeAt(i + 1)]; + let encoded3 = LOOKUP[base64.charCodeAt(i + 2)]; + let encoded4 = LOOKUP[base64.charCodeAt(i + 3)]; + + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + + return bytes; +} diff --git a/node_modules/for-each/.editorconfig b/node_modules/for-each/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..ac29adef0361c66b058a66a44ec2a0fd0b1a2207 --- /dev/null +++ b/node_modules/for-each/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 120 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/for-each/.eslintrc b/node_modules/for-each/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9b811fa447fbb1de7da08d719aa2753cc6bea806 --- /dev/null +++ b/node_modules/for-each/.eslintrc @@ -0,0 +1,30 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "func-style": 0, + "indent": [2, 4], + "max-nested-callbacks": [2, 3], + "max-params": [2, 3], + "max-statements": [2, 14], + "no-extra-parens": 0, + "no-invalid-this": 1, + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": 0, + "no-magic-numbers": 0, + }, + }, + ], +} diff --git a/node_modules/for-each/.github/FUNDING.yml b/node_modules/for-each/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ce5b3a62f36cd851c865de61b745b814b1ae4c6 --- /dev/null +++ b/node_modules/for-each/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/for-each +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/for-each/.github/SECURITY.md b/node_modules/for-each/.github/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..82e4285adc6285693cd6c06af02d606e09dd8fcd --- /dev/null +++ b/node_modules/for-each/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. diff --git a/node_modules/for-each/.nycrc b/node_modules/for-each/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..b7b8240afc9d1d7fb65126e9b13c3502dbd6abc5 --- /dev/null +++ b/node_modules/for-each/.nycrc @@ -0,0 +1,8 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/for-each/CHANGELOG.md b/node_modules/for-each/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..06b5bc0756671dae2c301f50834b035addb38454 --- /dev/null +++ b/node_modules/for-each/CHANGELOG.md @@ -0,0 +1,107 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v0.3.5](https://github.com/ljharb/for-each/compare/v0.3.4...v0.3.5) - 2025-02-10 + +### Commits + +- [New] add types [`6483c1e`](https://github.com/ljharb/for-each/commit/6483c1e9b6177e5ca9ba506188300c5a25de26c2) + +## [v0.3.4](https://github.com/ljharb/for-each/compare/v0.3.3...v0.3.4) - 2025-01-24 + +### Commits + +- [meta] use `auto-changelog` [`c16ee6a`](https://github.com/ljharb/for-each/commit/c16ee6a125eb3c6d30f626b4b02ec849a63fca28) +- [Tests] add github actions [`379b59c`](https://github.com/ljharb/for-each/commit/379b59c8f282c2281ba668e3e028ad6410afb99b) +- [meta] delete `.travis.yml` [`09e5c77`](https://github.com/ljharb/for-each/commit/09e5c779651215c41bd4727e266a5e7ebb3b0a4d) +- [Dev Deps] update eslint things [`9163b86`](https://github.com/ljharb/for-each/commit/9163b86435be325965f096ac17793a0e783b1c1e) +- [meta] consolidate eslintrc files [`f2ab52b`](https://github.com/ljharb/for-each/commit/f2ab52b6944fe8c1a189957889276950393eddb3) +- [meta] add `funding` field and `FUNDING.yml` [`05d21b3`](https://github.com/ljharb/for-each/commit/05d21b382ccd4627b283d1a31c49935c7d79fd57) +- [Tests] up to `node` `v10`; use `nvm install-latest-npm` [`7c06cbd`](https://github.com/ljharb/for-each/commit/7c06cbdabea81ba029cd466545dea5cb9f24f528) +- [Tests] add `nyc` [`0f4643e`](https://github.com/ljharb/for-each/commit/0f4643e6a572bdc6967a17be8e7b959600edbbd2) +- [meta] use `npmignore` [`39a975c`](https://github.com/ljharb/for-each/commit/39a975c8c6050586b93b5e0a98b20be44d1b38d4) +- [meta] remove unnecessary `licenses` key [`3d064f1`](https://github.com/ljharb/for-each/commit/3d064f12167c12d8e1d1ee1447ee58d8211c63e1) +- [Tests] use `npm audit` instead of long-dead `nsp` [`d4c722a`](https://github.com/ljharb/for-each/commit/d4c722a0f61f61d93965328f436f87421bce9973) +- [Dev Deps] update `tape` [`552c1ae`](https://github.com/ljharb/for-each/commit/552c1ae6a01728ff312d47605dbdb961ef0ccbcc) +- Update README.md [`d19acc2`](https://github.com/ljharb/for-each/commit/d19acc23624eed9d8f59b9fa64e6e3cba638aa52) +- [meta] add missing `engines.node` [`8889b49`](https://github.com/ljharb/for-each/commit/8889b49bd737d7a72c2a515eb2ee39a01c813bac) +- [meta] create SECURITY.md [`9069d42`](https://github.com/ljharb/for-each/commit/9069d42d245b02ae7c5f0c193fceb55427436e4e) +- [Deps] update `is-callable` [`bfa51d1`](https://github.com/ljharb/for-each/commit/bfa51d18018477843147bcdcc6cc63eb045151f5) + +## [v0.3.3](https://github.com/ljharb/for-each/compare/v0.3.2...v0.3.3) - 2018-06-01 + +### Commits + +- Add `npm run lint`, `npm run jscs`, and `npm run eslint` [`4a17d99`](https://github.com/ljharb/for-each/commit/4a17d99d7397dd2356530d238e0e6c37ef34a1d5) +- Style cleanup: [`1df6824`](https://github.com/ljharb/for-each/commit/1df6824d96bfc293c0c9e6b78143b602c8d94986) +- Update `eslint`, `tape`; use my personal shared `eslint` config. [`b8e7d85`](https://github.com/ljharb/for-each/commit/b8e7d850ec9010a7171d34297f7af74b90f28aac) +- [Tests] remove jscs [`37e3557`](https://github.com/ljharb/for-each/commit/37e355784b4261dcf5004158a72c4b8a6c6c524f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `tape`; fix scripts [`566045d`](https://github.com/ljharb/for-each/commit/566045d84f2ee5dff7cc14805c4fdb1d13d2624d) +- [Tests] up to `node` `v8`; newer npm breaks on older node [`07177dc`](https://github.com/ljharb/for-each/commit/07177dc9c8419b2a887c727ec576189a7c8e7837) +- Run `npm run lint` as part of tests. [`a34ea05`](https://github.com/ljharb/for-each/commit/a34ea05f729e0987007670d5693e093c56865ef6) +- Update `travis.yml` to test on the latest `node` and `io.js` [`354c843`](https://github.com/ljharb/for-each/commit/354c8434a166c7095c613e818c8d542fd1e2d630) +- Update `eslint` [`3601c93`](https://github.com/ljharb/for-each/commit/3601c9348e2cfb29ed3cfee352c2c95d4a8de87f) +- Update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`1aaff65`](https://github.com/ljharb/for-each/commit/1aaff65a55d8a054561251c6a2501c4dc42e1f99) +- Only use `Function#call` to call the callback if the receiver is supplied, for performance. [`54b4775`](https://github.com/ljharb/for-each/commit/54b477571b4d7c11edccafd94f2e16380892ee5d) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`, `nsp` [`6ba1cb8`](https://github.com/ljharb/for-each/commit/6ba1cb8a708e84ba4bb4067d31549829ec579d92) +- [Dev Deps] update `tape`, `eslint`, `jscs` [`8f5e1d5`](https://github.com/ljharb/for-each/commit/8f5e1d5fcabaf3abaa6ce2d3e6dd095f0dedfc4e) +- Add "license" to `package.json`, matching the LICENSE file. [`defc2c3`](https://github.com/ljharb/for-each/commit/defc2c35ffa7c9d4fbcf846f28b436f0083a381c) +- Update `eslint` [`05d1850`](https://github.com/ljharb/for-each/commit/05d18503dd0ec709f93df5c905bd2d0ce51323c3) +- [Tests] on `io.js` `v3.3`, `node` `v4.0` [`e8395a4`](https://github.com/ljharb/for-each/commit/e8395a43feef399299839c8d466ddd9dca0c3268) +- Add `npm run security` [`0a45177`](https://github.com/ljharb/for-each/commit/0a45177290b1de71094ddd322ef4a504458e901d) +- Only apps should have lockfiles. [`6268d7b`](https://github.com/ljharb/for-each/commit/6268d7b39edd06ef5a283c7afdb6c823077db777) +- [Dev Deps] update `nsp`, `tape`, `eslint` [`b95939f`](https://github.com/ljharb/for-each/commit/b95939f66a3dad590b3bc42c53535e77c1bfc114) +- Use `is-callable` instead of `is-function`, to cover ES6 environments with `Symbol.toStringTag` [`4095d33`](https://github.com/ljharb/for-each/commit/4095d334581c1caee92f595c299ffc479806dc3f) +- Test on `io.js` `v2.2` [`7b44f98`](https://github.com/ljharb/for-each/commit/7b44f98c217291a92385ddd3903d4974e049d762) +- Some old browsers choke on variables named "toString". [`4f1b626`](https://github.com/ljharb/for-each/commit/4f1b626eb91fcdc0e9018472a702aea713799190) +- Update `is-function`, `tape` [`3ceaf32`](https://github.com/ljharb/for-each/commit/3ceaf3240ef7d1b261cf510eb932cf540291187b) +- Test up to `io.js` `v3.0` [`3c1377a`](https://github.com/ljharb/for-each/commit/3c1377a31adf003323f4846a97e8f7c8fd51b5d2) +- [Deps] update `is-callable` [`f5c62d0`](https://github.com/ljharb/for-each/commit/f5c62d034b582a15bcb1f1cadace4e9c84f1780a) +- Test on `io.js` `v2.4` [`db86c85`](https://github.com/ljharb/for-each/commit/db86c85641d053a1dc4e570e8c8afbea915f78c0) +- Test on `io.js` `v2.3` [`2f04ca8`](https://github.com/ljharb/for-each/commit/2f04ca885adb4a8ccca658739f771a7f78522d03) + +## [v0.3.2](https://github.com/ljharb/for-each/compare/v0.3.1...v0.3.2) - 2014-01-07 + +### Merged + +- works down to IE6 [`#5`](https://github.com/ljharb/for-each/pull/5) + +## [v0.3.1](https://github.com/ljharb/for-each/compare/v0.3.0...v0.3.1) - 2014-01-06 + +## [v0.3.0](https://github.com/ljharb/for-each/compare/v0.2.0...v0.3.0) - 2014-01-06 + +### Merged + +- remove use of Object.keys [`#4`](https://github.com/ljharb/for-each/pull/4) +- Update tape. [`#3`](https://github.com/ljharb/for-each/pull/3) +- regex is not a function [`#2`](https://github.com/ljharb/for-each/pull/2) +- Add testling [`#1`](https://github.com/ljharb/for-each/pull/1) + +### Commits + +- Add testling. [`a24b521`](https://github.com/ljharb/for-each/commit/a24b52111937d509a3b5f58106c8835283de7146) +- Add array example to README [`9bd70c2`](https://github.com/ljharb/for-each/commit/9bd70c2ceafddfc734a80e0fea2bbac00afa963a) +- Regexes are considered functions in older browsers. [`403f649`](https://github.com/ljharb/for-each/commit/403f6490f903984adea1771af29c41fd2b1e4b64) +- Adding android browser to testling. [`a4c5825`](https://github.com/ljharb/for-each/commit/a4c5825bf8abd13589b9a9662c9d3deaf89cbf66) + +## [v0.2.0](https://github.com/ljharb/for-each/compare/v0.1.0...v0.2.0) - 2013-05-10 + +### Commits + +- Adding tests. [`7e74213`](https://github.com/ljharb/for-each/commit/7e74213d1b5d01b19249c3e3037302bd7fc74f1c) +- Adding proper array indexing, as well as string support. [`d36f794`](https://github.com/ljharb/for-each/commit/d36f794d6c0c5696bf1e4f8e79ae667858dfc11b) +- Use tape instead of tap. [`016a3cf`](https://github.com/ljharb/for-each/commit/016a3cf706c78037384d4c378b2ebe6e702cbb02) +- Requiring that the iterator is a function. [`cfedced`](https://github.com/ljharb/for-each/commit/cfedceda15ea2f7eb4acf079fb90ce17ec7da664) +- Adding myself as a contributor :-) [`ff28fca`](https://github.com/ljharb/for-each/commit/ff28fca8ec30f6fdbb7af87c74ed35688e60d07a) +- Adding node 0.10 to travis [`75f2460`](https://github.com/ljharb/for-each/commit/75f2460343d3ea58f91dad45f2eda478e3a4e412) + +## v0.1.0 - 2012-09-28 + +### Commits + +- first [`2d3a6ed`](https://github.com/ljharb/for-each/commit/2d3a6ed63036455847937cf00bec56b59ab36a9d) +- docs & travis [`ea4caad`](https://github.com/ljharb/for-each/commit/ea4caad8a8768992dcce29998e226484beed841c) diff --git a/node_modules/for-each/LICENSE b/node_modules/for-each/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..53f19aa771439a54bcc31897e36fb2a8ad3c11ef --- /dev/null +++ b/node_modules/for-each/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2012 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/node_modules/for-each/README.md b/node_modules/for-each/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b76561ef1f70c86551d7631075c611665bc11714 --- /dev/null +++ b/node_modules/for-each/README.md @@ -0,0 +1,39 @@ +# for-each [![build status][1]][2] + +[![browser support][3]][4] + +A better forEach. + +## Example + +Like `Array.prototype.forEach` but works on objects. + +```js +var forEach = require("for-each") + +forEach({ key: "value" }, function (value, key, object) { + /* code */ +}) +``` + +As a bonus, it's also a perfectly function shim/polyfill for arrays too! + +```js +var forEach = require("for-each") + +forEach([1, 2, 3], function (value, index, array) { + /* code */ +}) +``` + +## Installation + +`npm install for-each` + +## MIT Licenced + + [1]: https://secure.travis-ci.org/Raynos/for-each.png + [2]: http://travis-ci.org/Raynos/for-each + [3]: https://ci.testling.com/Raynos/for-each.png + [4]: https://ci.testling.com/Raynos/for-each + diff --git a/node_modules/for-each/index.d.ts b/node_modules/for-each/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..90f98de4f7b74b25872d8c040d22b25c513d8811 --- /dev/null +++ b/node_modules/for-each/index.d.ts @@ -0,0 +1,35 @@ +declare function forEach( + arr: O, + callback: (this: This | void, value: O[number], index: number, array: O) => void, + thisArg?: This, +): void; + +declare function forEach, This = undefined>( + arr: O, + callback: (this: This | void, value: O[number], index: number, array: O) => void, + thisArg?: This, +): void; + +declare function forEach( + obj: O, + callback: (this: This | void, value: O[keyof O], key: keyof O, obj: O) => void, + thisArg?: This, +): void; + +declare function forEach( + str: O, + callback: (this: This | void, value: O[number], index: number, str: O) => void, + thisArg: This, +): void; + +export = forEach; + +declare function forEachInternal void, This = undefined>( + value: O, + callback: C, + thisArg?: This, +): void; + +declare namespace forEach { + export type _internal = typeof forEachInternal; +} diff --git a/node_modules/for-each/index.js b/node_modules/for-each/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0af3c44eb49fb153b1c7bc05d812045c9c4acd81 --- /dev/null +++ b/node_modules/for-each/index.js @@ -0,0 +1,69 @@ +'use strict'; + +var isCallable = require('is-callable'); + +var toStr = Object.prototype.toString; +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** @type {(arr: A, iterator: (this: This | void, value: A[number], index: number, arr: A) => void, receiver: This | undefined) => void} */ +var forEachArray = function forEachArray(array, iterator, receiver) { + for (var i = 0, len = array.length; i < len; i++) { + if (hasOwnProperty.call(array, i)) { + if (receiver == null) { + iterator(array[i], i, array); + } else { + iterator.call(receiver, array[i], i, array); + } + } + } +}; + +/** @type {(string: S, iterator: (this: This | void, value: S[number], index: number, string: S) => void, receiver: This | undefined) => void} */ +var forEachString = function forEachString(string, iterator, receiver) { + for (var i = 0, len = string.length; i < len; i++) { + // no such thing as a sparse string. + if (receiver == null) { + iterator(string.charAt(i), i, string); + } else { + iterator.call(receiver, string.charAt(i), i, string); + } + } +}; + +/** @type {(obj: O, iterator: (this: This | void, value: O[keyof O], index: keyof O, obj: O) => void, receiver: This | undefined) => void} */ +var forEachObject = function forEachObject(object, iterator, receiver) { + for (var k in object) { + if (hasOwnProperty.call(object, k)) { + if (receiver == null) { + iterator(object[k], k, object); + } else { + iterator.call(receiver, object[k], k, object); + } + } + } +}; + +/** @type {(x: unknown) => x is readonly unknown[]} */ +function isArray(x) { + return toStr.call(x) === '[object Array]'; +} + +/** @type {import('.')._internal} */ +module.exports = function forEach(list, iterator, thisArg) { + if (!isCallable(iterator)) { + throw new TypeError('iterator must be a function'); + } + + var receiver; + if (arguments.length >= 3) { + receiver = thisArg; + } + + if (isArray(list)) { + forEachArray(list, iterator, receiver); + } else if (typeof list === 'string') { + forEachString(list, iterator, receiver); + } else { + forEachObject(list, iterator, receiver); + } +}; diff --git a/node_modules/for-each/package.json b/node_modules/for-each/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bf0f5cded82e9638fc05ab93340ea1d583ffa7bd --- /dev/null +++ b/node_modules/for-each/package.json @@ -0,0 +1,76 @@ +{ + "name": "for-each", + "version": "0.3.5", + "description": "A better forEach", + "keywords": [], + "author": "Raynos ", + "repository": { + "type": "git", + "url": "https://github.com/Raynos/for-each.git" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "main": "index", + "homepage": "https://github.com/Raynos/for-each", + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "bugs": { + "url": "https://github.com/Raynos/for-each/issues", + "email": "raynos2@gmail.com" + }, + "license": "MIT", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "nyc tape 'test/*.js'", + "posttest": "npx npm@\">= 10.2\" audit --production", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "dependencies": { + "is-callable": "^1.2.7" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.3", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/is-callable": "^1.1.2", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "eslint": "=8.8.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/test.js" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/for-each/test/test.js b/node_modules/for-each/test/test.js new file mode 100644 index 0000000000000000000000000000000000000000..455d247eba87a5c7c429c857cbd58f8b816b54c4 --- /dev/null +++ b/node_modules/for-each/test/test.js @@ -0,0 +1,224 @@ +'use strict'; + +var test = require('tape'); +var forEach = require('../'); + +test('forEach calls each iterator', function (t) { + var count = 0; + t.plan(4); + + forEach({ a: 1, b: 2 }, function (value, key) { + if (count === 0) { + t.equal(value, 1); + t.equal(key, 'a'); + } else { + t.equal(value, 2); + t.equal(key, 'b'); + } + count += 1; + }); +}); + +test('forEach calls iterator with correct this value', function (t) { + var thisValue = {}; + + t.plan(1); + + forEach([0], function () { + t.equal(this, thisValue); + }, thisValue); +}); + +test('second argument: iterator', function (t) { + /** @type {unknown[]} */ + var arr = []; + + // @ts-expect-error + t['throws'](function () { forEach(arr); }, TypeError, 'undefined is not a function'); + // @ts-expect-error + t['throws'](function () { forEach(arr, null); }, TypeError, 'null is not a function'); + // @ts-expect-error + t['throws'](function () { forEach(arr, ''); }, TypeError, 'string is not a function'); + // @ts-expect-error + t['throws'](function () { forEach(arr, /a/); }, TypeError, 'regex is not a function'); + // @ts-expect-error + t['throws'](function () { forEach(arr, true); }, TypeError, 'true is not a function'); + // @ts-expect-error + t['throws'](function () { forEach(arr, false); }, TypeError, 'false is not a function'); + // @ts-expect-error + t['throws'](function () { forEach(arr, NaN); }, TypeError, 'NaN is not a function'); + // @ts-expect-error + t['throws'](function () { forEach(arr, 42); }, TypeError, '42 is not a function'); + + t.doesNotThrow(function () { forEach(arr, function () {}); }, 'function is a function'); + // @ts-expect-error TODO fixme + t.doesNotThrow(function () { forEach(arr, setTimeout); }, 'setTimeout is a function'); + + /* eslint-env browser */ + if (typeof window !== 'undefined') { + t.doesNotThrow(function () { forEach(arr, window.alert); }, 'alert is a function'); + } + + t.end(); +}); + +test('array', function (t) { + var arr = /** @type {const} */ ([1, 2, 3]); + + t.test('iterates over every item', function (st) { + var index = 0; + forEach(arr, function () { index += 1; }); + st.equal(index, arr.length, 'iterates ' + arr.length + ' times'); + st.end(); + }); + + t.test('first iterator argument', function (st) { + var index = 0; + st.plan(arr.length); + + forEach(arr, function (item) { + st.equal(arr[index], item, 'item ' + index + ' is passed as first argument'); + index += 1; + }); + + st.end(); + }); + + t.test('second iterator argument', function (st) { + var counter = 0; + st.plan(arr.length); + + forEach(arr, function (_item, index) { + st.equal(counter, index, 'index ' + index + ' is passed as second argument'); + counter += 1; + }); + + st.end(); + }); + + t.test('third iterator argument', function (st) { + st.plan(arr.length); + + forEach(arr, function (_item, _index, array) { + st.deepEqual(arr, array, 'array is passed as third argument'); + }); + + st.end(); + }); + + t.test('context argument', function (st) { + var context = {}; + + forEach([], function () { + st.equal(this, context, '"this" is the passed context'); + }, context); + + st.end(); + }); + + t.end(); +}); + +test('object', function (t) { + var obj = { + a: 1, + b: 2, + c: 3 + }; + var keys = /** @type {const} */ (['a', 'b', 'c']); + + /** @constructor */ + function F() { + this.a = 1; + this.b = 2; + } + F.prototype.c = 3; + var fKeys = /** @type {const} */ (['a', 'b']); + + t.test('iterates over every object literal key', function (st) { + var counter = 0; + + forEach(obj, function () { counter += 1; }); + + st.equal(counter, keys.length, 'iterated ' + counter + ' times'); + + st.end(); + }); + + t.test('iterates only over own keys', function (st) { + var counter = 0; + + forEach(new F(), function () { counter += 1; }); + + st.equal(counter, fKeys.length, 'iterated ' + fKeys.length + ' times'); + + st.end(); + }); + + t.test('first iterator argument', function (st) { + var index = 0; + st.plan(keys.length); + + forEach(obj, function (item) { + st.equal(obj[keys[index]], item, 'item at key ' + keys[index] + ' is passed as first argument'); + index += 1; + }); + + st.end(); + }); + + t.test('second iterator argument', function (st) { + var counter = 0; + st.plan(keys.length); + + forEach(obj, function (_item, key) { + st.equal(keys[counter], key, 'key ' + key + ' is passed as second argument'); + counter += 1; + }); + + st.end(); + }); + + t.test('third iterator argument', function (st) { + st.plan(keys.length); + + forEach(obj, function (_item, _key, object) { + st.deepEqual(obj, object, 'object is passed as third argument'); + }); + + st.end(); + }); + + t.test('context argument', function (st) { + var context = {}; + + forEach({}, function () { + st.equal(this, context, '"this" is the passed context'); + }, context); + + st.end(); + }); + + t.end(); +}); + +test('string', function (t) { + var str = /** @type {const} */ ('str'); + + t.test('second iterator argument', function (st) { + var counter = 0; + st.plan((str.length * 2) + 1); + + forEach(str, function (item, index) { + st.equal(counter, index, 'index ' + index + ' is passed as second argument'); + st.equal(str.charAt(index), item); + counter += 1; + }); + + st.equal(counter, str.length, 'iterates ' + str.length + ' times'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/for-each/tsconfig.json b/node_modules/for-each/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..a6aec2c821b73bc8f771c09feb6688a8f9cf3c61 --- /dev/null +++ b/node_modules/for-each/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/foreground-child/LICENSE b/node_modules/foreground-child/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2d80720fe669c96dd0cfec56a90939666086e701 --- /dev/null +++ b/node_modules/foreground-child/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015-2023 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/foreground-child/README.md b/node_modules/foreground-child/README.md new file mode 100644 index 0000000000000000000000000000000000000000..477ca57178e39045cd30a5d83f40b02632d95b35 --- /dev/null +++ b/node_modules/foreground-child/README.md @@ -0,0 +1,128 @@ +# foreground-child + +Run a child as if it's the foreground process. Give it stdio. Exit +when it exits. + +Mostly this module is here to support some use cases around +wrapping child processes for test coverage and such. But it's +also generally useful any time you want one program to execute +another as if it's the "main" process, for example, if a program +takes a `--cmd` argument to execute in some way. + +## USAGE + +```js +import { foregroundChild } from 'foreground-child' +// hybrid module, this also works: +// const { foregroundChild } = require('foreground-child') + +// cats out this file +const child = foregroundChild('cat', [__filename]) + +// At this point, it's best to just do nothing else. +// return or whatever. +// If the child gets a signal, or just exits, then this +// parent process will exit in the same way. +``` + +You can provide custom spawn options by passing an object after +the program and arguments: + +```js +const child = foregroundChild(`cat ${__filename}`, { shell: true }) +``` + +A callback can optionally be provided, if you want to perform an +action before your foreground-child exits: + +```js +const child = foregroundChild('cat', [__filename], spawnOptions, () => { + doSomeActions() +}) +``` + +The callback can return a Promise in order to perform +asynchronous actions. If the callback does not return a promise, +then it must complete its actions within a single JavaScript +tick. + +```js +const child = foregroundChild('cat', [__filename], async () => { + await doSomeAsyncActions() +}) +``` + +If the callback throws or rejects, then it will be unhandled, and +node will exit in error. + +If the callback returns a string value, then that will be used as +the signal to exit the parent process. If it returns a number, +then that number will be used as the parent exit status code. If +it returns boolean `false`, then the parent process will not be +terminated. If it returns `undefined`, then it will exit with the +same signal/code as the child process. + +## Caveats + +The "normal" standard IO file descriptors (0, 1, and 2 for stdin, +stdout, and stderr respectively) are shared with the child process. +Additionally, if there is an IPC channel set up in the parent, then +messages are proxied to the child on file descriptor 3. + +In Node, it's possible to also map arbitrary file descriptors +into a child process. In these cases, foreground-child will not +map the file descriptors into the child. If file descriptors 0, +1, or 2 are used for the IPC channel, then strange behavior may +happen (like printing IPC messages to stderr, for example). + +Note that a SIGKILL will always kill the parent process, but +will not proxy the signal to the child process, because SIGKILL +cannot be caught. In order to address this, a special "watchdog" +child process is spawned which will send a SIGKILL to the child +process if it does not terminate within half a second after the +watchdog receives a SIGHUP due to its parent terminating. + +On Windows, issuing a `process.kill(process.pid, signal)` with a +fatal termination signal may cause the process to exit with a `1` +status code rather than reporting the signal properly. This +module tries to do the right thing, but on Windows systems, you +may see that incorrect result. There is as far as I'm aware no +workaround for this. + +## util: `foreground-child/proxy-signals` + +If you just want to proxy the signals to a child process that the +main process receives, you can use the `proxy-signals` export +from this package. + +```js +import { proxySignals } from 'foreground-child/proxy-signals' + +const childProcess = spawn('command', ['some', 'args']) +proxySignals(childProcess) +``` + +Now, any fatal signal received by the current process will be +proxied to the child process. + +It doesn't go in the other direction; ie, signals sent to the +child process will not affect the parent. For that, listen to the +child `exit` or `close` events, and handle them appropriately. + +## util: `foreground-child/watchdog` + +If you are spawning a child process, and want to ensure that it +isn't left dangling if the parent process exits, you can use the +watchdog utility exported by this module. + +```js +import { watchdog } from 'foreground-child/watchdog' + +const childProcess = spawn('command', ['some', 'args']) +const watchdogProcess = watchdog(childProcess) + +// watchdogProcess is a reference to the process monitoring the +// parent and child. There's usually no reason to do anything +// with it, as it's silent and will terminate +// automatically when it's no longer needed. +``` diff --git a/node_modules/foreground-child/package.json b/node_modules/foreground-child/package.json new file mode 100644 index 0000000000000000000000000000000000000000..75f5b9969b282b0a269b976afd251ded58be17ed --- /dev/null +++ b/node_modules/foreground-child/package.json @@ -0,0 +1,106 @@ +{ + "name": "foreground-child", + "version": "3.3.1", + "description": "Run a child as if it's the foreground process. Give it stdio. Exit when it exits.", + "main": "./dist/commonjs/index.js", + "types": "./dist/commonjs/index.d.ts", + "exports": { + "./watchdog": { + "import": { + "types": "./dist/esm/watchdog.d.ts", + "default": "./dist/esm/watchdog.js" + }, + "require": { + "types": "./dist/commonjs/watchdog.d.ts", + "default": "./dist/commonjs/watchdog.js" + } + }, + "./proxy-signals": { + "import": { + "types": "./dist/esm/proxy-signals.d.ts", + "default": "./dist/esm/proxy-signals.js" + }, + "require": { + "types": "./dist/commonjs/proxy-signals.d.ts", + "default": "./dist/commonjs/proxy-signals.js" + } + }, + "./package.json": "./package.json", + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/commonjs/index.d.ts", + "default": "./dist/commonjs/index.js" + } + } + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=14" + }, + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "prepare": "tshy", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "tap", + "snap": "tap", + "format": "prettier --write . --log-level warn", + "typedoc": "typedoc --tsconfig .tshy/esm.json ./src/*.ts" + }, + "prettier": { + "experimentalTernaries": true, + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "tap": { + "typecheck": true + }, + "repository": { + "type": "git", + "url": "git+https://github.com/tapjs/foreground-child.git" + }, + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "license": "ISC", + "devDependencies": { + "@types/cross-spawn": "^6.0.2", + "@types/node": "^18.15.11", + "@types/tap": "^15.0.8", + "prettier": "^3.3.2", + "tap": "^21.1.0", + "tshy": "^3.0.2", + "typedoc": "^0.24.2", + "typescript": "^5.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "tshy": { + "exports": { + "./watchdog": "./src/watchdog.ts", + "./proxy-signals": "./src/proxy-signals.ts", + "./package.json": "./package.json", + ".": "./src/index.ts" + } + }, + "type": "module", + "module": "./dist/esm/index.js" +} diff --git a/node_modules/form-data/CHANGELOG.md b/node_modules/form-data/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..cf130d2eab71ee5472c9eaf848322d5e8f1c4d37 --- /dev/null +++ b/node_modules/form-data/CHANGELOG.md @@ -0,0 +1,686 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v4.0.6](https://github.com/form-data/form-data/compare/v4.0.5...v4.0.6) - 2026-06-12 + +### Commits + +- [Fix] escape CR, LF, and `"` in field names and filenames [`8dff42c`](https://github.com/form-data/form-data/commit/8dff42c6da654ed4e7ad4acb7f8ccd3831217c99) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `tape` [`f31d21e`](https://github.com/form-data/form-data/commit/f31d21ef10bf46e46344c3ee4f99acbef6be43e1) +- [Deps] update `hasown`, `mime-types` [`92ae0eb`](https://github.com/form-data/form-data/commit/92ae0eb5da94d6f01925d5f4fcffb2a1e50ed7cd) +- [Dev Deps] update `js-randomness-predictor` [`67b0f65`](https://github.com/form-data/form-data/commit/67b0f65c2e0b065a511d42227d35e4d367644e97) + +## [v4.0.5](https://github.com/form-data/form-data/compare/v4.0.4...v4.0.5) - 2025-11-17 + +### Commits + +- [Tests] Switch to newer v8 prediction library; enable node 24 testing [`16e0076`](https://github.com/form-data/form-data/commit/16e00765342106876f98a1c9703314006c9e937a) +- [Dev Deps] update `@ljharb/eslint-config`, `eslint` [`5822467`](https://github.com/form-data/form-data/commit/5822467f0ec21f6ad613c1c90856375e498793c7) +- [Fix] set Symbol.toStringTag in the proper place [`76d0dee`](https://github.com/form-data/form-data/commit/76d0dee43933b5e167f7f09e5d9cbbd1cf911aa7) + +## [v4.0.4](https://github.com/form-data/form-data/compare/v4.0.3...v4.0.4) - 2025-07-16 + +### Commits + +- [meta] add `auto-changelog` [`811f682`](https://github.com/form-data/form-data/commit/811f68282fab0315209d0e2d1c44b6c32ea0d479) +- [Tests] handle predict-v8-randomness failures in node < 17 and node > 23 [`1d11a76`](https://github.com/form-data/form-data/commit/1d11a76434d101f22fdb26b8aef8615f28b98402) +- [Fix] Switch to using `crypto` random for boundary values [`3d17230`](https://github.com/form-data/form-data/commit/3d1723080e6577a66f17f163ecd345a21d8d0fd0) +- [Tests] fix linting errors [`5e34080`](https://github.com/form-data/form-data/commit/5e340800b5f8914213e4e0378c084aae71cfd73a) +- [meta] actually ensure the readme backup isn’t published [`316c82b`](https://github.com/form-data/form-data/commit/316c82ba93fd4985af757b771b9a1f26d3b709ef) +- [Dev Deps] update `@ljharb/eslint-config` [`58c25d7`](https://github.com/form-data/form-data/commit/58c25d76406a5b0dfdf54045cf252563f2bbda8d) +- [meta] fix readme capitalization [`2300ca1`](https://github.com/form-data/form-data/commit/2300ca19595b0ee96431e868fe2a40db79e41c61) + +## [v4.0.3](https://github.com/form-data/form-data/compare/v4.0.2...v4.0.3) - 2025-06-05 + +### Fixed + +- [Fix] `append`: avoid a crash on nullish values [`#577`](https://github.com/form-data/form-data/issues/577) + +### Commits + +- [eslint] use a shared config [`426ba9a`](https://github.com/form-data/form-data/commit/426ba9ac440f95d1998dac9a5cd8d738043b048f) +- [eslint] fix some spacing issues [`2094191`](https://github.com/form-data/form-data/commit/20941917f0e9487e68c564ebc3157e23609e2939) +- [Refactor] use `hasown` [`81ab41b`](https://github.com/form-data/form-data/commit/81ab41b46fdf34f5d89d7ff30b513b0925febfaa) +- [Fix] validate boundary type in `setBoundary()` method [`8d8e469`](https://github.com/form-data/form-data/commit/8d8e4693093519f7f18e3c597d1e8df8c493de9e) +- [Tests] add tests to check the behavior of `getBoundary` with non-strings [`837b8a1`](https://github.com/form-data/form-data/commit/837b8a1f7562bfb8bda74f3fc538adb7a5858995) +- [Dev Deps] remove unused deps [`870e4e6`](https://github.com/form-data/form-data/commit/870e4e665935e701bf983a051244ab928e62d58e) +- [meta] remove local commit hooks [`e6e83cc`](https://github.com/form-data/form-data/commit/e6e83ccb545a5619ed6cd04f31d5c2f655eb633e) +- [Dev Deps] update `eslint` [`4066fd6`](https://github.com/form-data/form-data/commit/4066fd6f65992b62fa324a6474a9292a4f88c916) +- [meta] fix scripts to use prepublishOnly [`c4bbb13`](https://github.com/form-data/form-data/commit/c4bbb13c0ef669916657bc129341301b1d331d75) + +## [v4.0.2](https://github.com/form-data/form-data/compare/v4.0.1...v4.0.2) - 2025-02-14 + +### Merged + +- [Fix] set `Symbol.toStringTag` when available [`#573`](https://github.com/form-data/form-data/pull/573) +- [Fix] set `Symbol.toStringTag` when available [`#573`](https://github.com/form-data/form-data/pull/573) +- fix (npmignore): ignore temporary build files [`#532`](https://github.com/form-data/form-data/pull/532) +- fix (npmignore): ignore temporary build files [`#532`](https://github.com/form-data/form-data/pull/532) + +### Fixed + +- [Fix] set `Symbol.toStringTag` when available (#573) [`#396`](https://github.com/form-data/form-data/issues/396) +- [Fix] set `Symbol.toStringTag` when available (#573) [`#396`](https://github.com/form-data/form-data/issues/396) +- [Fix] set `Symbol.toStringTag` when available [`#396`](https://github.com/form-data/form-data/issues/396) + +### Commits + +- Merge tags v2.5.3 and v3.0.3 [`92613b9`](https://github.com/form-data/form-data/commit/92613b9208556eb4ebc482fdf599fae111626fb6) +- [Tests] migrate from travis to GHA [`806eda7`](https://github.com/form-data/form-data/commit/806eda77740e6e3c67c7815afb216f2e1f187ba5) +- [Tests] migrate from travis to GHA [`8fdb3bc`](https://github.com/form-data/form-data/commit/8fdb3bc6b5d001f8909a9fca391d1d1d97ef1d79) +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`7fecefe`](https://github.com/form-data/form-data/commit/7fecefe4ba8f775634aff86a698776ad95ecffb5) +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`6e682d4`](https://github.com/form-data/form-data/commit/6e682d4bd41de7e80de41e3c4ee10f23fcc3dd00) +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`df3c1e6`](https://github.com/form-data/form-data/commit/df3c1e6f0937f47a782dc4573756a54987f31dde) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `cross-spawn`, `eslint`, `formidable`, `in-publish`, `pkgfiles`, `pre-commit`, `puppeteer`, `request`, `tape`, `typescript` [`8261fcb`](https://github.com/form-data/form-data/commit/8261fcb8bf5944d30ae3bd04b91b71d6a9932ef4) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `cross-spawn`, `eslint`, `formidable`, `in-publish`, `pkgfiles`, `pre-commit`, `puppeteer`, `request`, `tape`, `typescript` [`fb66cb7`](https://github.com/form-data/form-data/commit/fb66cb740e29fb170eee947d4be6fdf82d6659af) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `eslint`, `formidable`, `in-publish`, `phantomjs-prebuilt`, `pkgfiles`, `pre-commit`, `request`, `tape`, `typescript` [`819f6b7`](https://github.com/form-data/form-data/commit/819f6b7a543306a891fca37c3a06d0ff4a734422) +- [eslint] clean up ignores [`3217b3d`](https://github.com/form-data/form-data/commit/3217b3ded8e382e51171d5c74c6038a21cc54440) +- [eslint] clean up ignores [`3a9d480`](https://github.com/form-data/form-data/commit/3a9d480232dbcbc07260ad84c3da4975d9a3ae9e) +- [Fix] `Buffer.from` and `Buffer.alloc` require node 4+ [`c499f76`](https://github.com/form-data/form-data/commit/c499f76f1faac1ddbf210c45217038e4c1e02337) +- Only apps should have lockfiles [`b82f590`](https://github.com/form-data/form-data/commit/b82f59093cdbadb4b7ec0922d33ae7ab048b82ff) +- Only apps should have lockfiles [`b170ee2`](https://github.com/form-data/form-data/commit/b170ee2b22b4c695c363b811c0c553d2fb1bbd79) +- [Deps] update `combined-stream`, `mime-types` [`6b1ca1d`](https://github.com/form-data/form-data/commit/6b1ca1dc7362a1b1c3a99a885516cca4b7eb817f) +- [Dev Deps] pin `request` which via `tough-cookie` ^2.4 depends on `psl` [`e5df7f2`](https://github.com/form-data/form-data/commit/e5df7f24383342264bd73dee3274818a40d04065) +- [Deps] update `mime-types` [`5a5bafe`](https://github.com/form-data/form-data/commit/5a5bafee894fead10da49e1fa2b084e17f2e1034) +- Bumped version 2.5.3 [`9457283`](https://github.com/form-data/form-data/commit/9457283e1dce6122adc908fdd7442cfc54cabe7a) +- [Dev Deps] pin `request` which via `tough-cookie` ^2.4 depends on `psl` [`9dbe192`](https://github.com/form-data/form-data/commit/9dbe192be3db215eac4d9c0b980470a5c2c030c6) +- Merge tags v2.5.2 and v3.0.2 [`d53265d`](https://github.com/form-data/form-data/commit/d53265d86c5153f535ec68eb107548b1b2883576) +- Bumped version 2.5.2 [`7020dd4`](https://github.com/form-data/form-data/commit/7020dd4c1260370abc40e86e3dfe49c5d576fbda) +- [Dev Deps] downgrade `cross-spawn` [`3fc1a9b`](https://github.com/form-data/form-data/commit/3fc1a9b62ddf1fe77a2bd6bd3476e4c0a9e01a88) +- fix: move util.isArray to Array.isArray (#564) [`edb555a`](https://github.com/form-data/form-data/commit/edb555a811f6f7e4668db4831551cf41c1de1cac) +- fix: move util.isArray to Array.isArray (#564) [`10418d1`](https://github.com/form-data/form-data/commit/10418d1fe4b0d65fe020eafe3911feb5ad5e2bd6) + +## [v4.0.1](https://github.com/form-data/form-data/compare/v4.0.0...v4.0.1) - 2024-10-10 + +### Commits + +- [Tests] migrate from travis to GHA [`757b4e3`](https://github.com/form-data/form-data/commit/757b4e32e95726aec9bdcc771fb5a3b564d88034) +- [eslint] clean up ignores [`e8f0d80`](https://github.com/form-data/form-data/commit/e8f0d80cd7cd424d1488532621ec40a33218b30b) +- fix (npmignore): ignore temporary build files [`335ad19`](https://github.com/form-data/form-data/commit/335ad19c6e17dc2d7298ffe0e9b37ba63600e94b) +- fix: move util.isArray to Array.isArray [`440d3be`](https://github.com/form-data/form-data/commit/440d3bed752ac2f9213b4c2229dbccefe140e5fa) + +## [v4.0.0](https://github.com/form-data/form-data/compare/v3.0.5...v4.0.0) - 2021-02-15 + +### Merged + +- Handle custom stream [`#382`](https://github.com/form-data/form-data/pull/382) + +### Commits + +- Fix typo [`e705c0a`](https://github.com/form-data/form-data/commit/e705c0a1fdaf90d21501f56460b93e43a18bd435) +- Update README for custom stream behavior [`6dd8624`](https://github.com/form-data/form-data/commit/6dd8624b2999e32768d62752c9aae5845a803b0d) + +## [v3.0.5](https://github.com/form-data/form-data/compare/v3.0.4...v3.0.5) - 2026-06-12 + +### Commits + +- [Fix] escape CR, LF, and `"` in field names and filenames [`8777e67`](https://github.com/form-data/form-data/commit/8777e67fbd0282d3dcba81f974fbdd91062c5b23) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `eslint`, `tape` [`27c61a5`](https://github.com/form-data/form-data/commit/27c61a5deed84798be105c96605cb8bd00502dcd) +- [Deps] update `hasown` [`6a8a1c6`](https://github.com/form-data/form-data/commit/6a8a1c6d04da36e15c80b16ecc4c0265082b3213) + +## [v3.0.4](https://github.com/form-data/form-data/compare/v3.0.3...v3.0.4) - 2025-07-16 + +### Fixed + +- [Fix] `append`: avoid a crash on nullish values [`#577`](https://github.com/form-data/form-data/issues/577) + +### Commits + +- [eslint] update linting config [`f5e7eb0`](https://github.com/form-data/form-data/commit/f5e7eb024bc3fc7e2074ff80f143a4f4cbc1dbda) +- [meta] add `auto-changelog` [`d2eb290`](https://github.com/form-data/form-data/commit/d2eb290a3e47ed5bcad7020d027daa15b3cf5ef5) +- [Tests] handle predict-v8-randomness failures in node < 17 and node > 23 [`e8c574c`](https://github.com/form-data/form-data/commit/e8c574cb07ff3a0de2ecc0912d783ef22e190c1f) +- [Fix] Switch to using `crypto` random for boundary values [`c6ced61`](https://github.com/form-data/form-data/commit/c6ced61d4fae8f617ee2fd692133ed87baa5d0fd) +- [Refactor] use `hasown` [`1a78b5d`](https://github.com/form-data/form-data/commit/1a78b5dd05e508d67e97764d812ac7c6d92ea88d) +- [Fix] validate boundary type in `setBoundary()` method [`70bbaa0`](https://github.com/form-data/form-data/commit/70bbaa0b395ca0fb975c309de8d7286979254cc4) +- [Tests] add tests to check the behavior of `getBoundary` with non-strings [`b22a64e`](https://github.com/form-data/form-data/commit/b22a64ef94ba4f3f6ff7d1ac72a54cca128567df) +- [meta] actually ensure the readme backup isn’t published [`0150851`](https://github.com/form-data/form-data/commit/01508513ffb26fd662ae7027834b325af8efb9ea) +- [meta] remove local commit hooks [`fc42bb9`](https://github.com/form-data/form-data/commit/fc42bb9315b641bfa6dae51cb4e188a86bb04769) +- [Dev Deps] remove unused deps [`a14d09e`](https://github.com/form-data/form-data/commit/a14d09ea8ed7e0a2e1705269ce6fb54bb7ee6bdb) +- [meta] fix scripts to use prepublishOnly [`11d9f73`](https://github.com/form-data/form-data/commit/11d9f7338f18a59b431832a3562b49baece0a432) +- [meta] fix readme capitalization [`fc38b48`](https://github.com/form-data/form-data/commit/fc38b4834a117a1856f3d877eb2f5b7496a24932) + +## [v3.0.3](https://github.com/form-data/form-data/compare/v3.0.2...v3.0.3) - 2025-02-14 + +### Merged + +- [Fix] set `Symbol.toStringTag` when available [`#573`](https://github.com/form-data/form-data/pull/573) + +### Fixed + +- [Fix] set `Symbol.toStringTag` when available (#573) [`#396`](https://github.com/form-data/form-data/issues/396) + +### Commits + +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`7fecefe`](https://github.com/form-data/form-data/commit/7fecefe4ba8f775634aff86a698776ad95ecffb5) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `cross-spawn`, `eslint`, `formidable`, `in-publish`, `pkgfiles`, `pre-commit`, `puppeteer`, `request`, `tape`, `typescript` [`8261fcb`](https://github.com/form-data/form-data/commit/8261fcb8bf5944d30ae3bd04b91b71d6a9932ef4) +- Only apps should have lockfiles [`b82f590`](https://github.com/form-data/form-data/commit/b82f59093cdbadb4b7ec0922d33ae7ab048b82ff) +- [Dev Deps] pin `request` which via `tough-cookie` ^2.4 depends on `psl` [`e5df7f2`](https://github.com/form-data/form-data/commit/e5df7f24383342264bd73dee3274818a40d04065) +- [Deps] update `mime-types` [`5a5bafe`](https://github.com/form-data/form-data/commit/5a5bafee894fead10da49e1fa2b084e17f2e1034) + +## [v3.0.2](https://github.com/form-data/form-data/compare/v3.0.1...v3.0.2) - 2024-10-10 + +### Merged + +- fix (npmignore): ignore temporary build files [`#532`](https://github.com/form-data/form-data/pull/532) + +### Commits + +- [Tests] migrate from travis to GHA [`8fdb3bc`](https://github.com/form-data/form-data/commit/8fdb3bc6b5d001f8909a9fca391d1d1d97ef1d79) +- [eslint] clean up ignores [`3217b3d`](https://github.com/form-data/form-data/commit/3217b3ded8e382e51171d5c74c6038a21cc54440) +- fix: move util.isArray to Array.isArray (#564) [`edb555a`](https://github.com/form-data/form-data/commit/edb555a811f6f7e4668db4831551cf41c1de1cac) + +## [v3.0.1](https://github.com/form-data/form-data/compare/v3.0.0...v3.0.1) - 2021-02-15 + +### Merged + +- Fix typo: ads -> adds [`#451`](https://github.com/form-data/form-data/pull/451) + +### Commits + +- feat: add setBoundary method [`55d90ce`](https://github.com/form-data/form-data/commit/55d90ce4a4c22b0ea0647991d85cb946dfb7395b) + +## [v3.0.0](https://github.com/form-data/form-data/compare/v2.5.6...v3.0.0) - 2019-11-05 + +### Merged + +- Update Readme.md [`#449`](https://github.com/form-data/form-data/pull/449) +- Update package.json [`#448`](https://github.com/form-data/form-data/pull/448) +- fix memory leak [`#447`](https://github.com/form-data/form-data/pull/447) +- form-data: Replaced PhantomJS Dependency [`#442`](https://github.com/form-data/form-data/pull/442) +- Fix constructor options in Typescript definitions [`#446`](https://github.com/form-data/form-data/pull/446) +- Fix the getHeaders method signatures [`#434`](https://github.com/form-data/form-data/pull/434) +- Update combined-stream (fixes #422) [`#424`](https://github.com/form-data/form-data/pull/424) + +### Fixed + +- Merge pull request #424 from botgram/update-combined-stream [`#422`](https://github.com/form-data/form-data/issues/422) +- Update combined-stream (fixes #422) [`#422`](https://github.com/form-data/form-data/issues/422) + +### Commits + +- Add readable stream options to constructor type [`80c8f74`](https://github.com/form-data/form-data/commit/80c8f746bcf4c0418ae35fbedde12fb8c01e2748) +- Fixed: getHeaders method signatures [`f4ca7f8`](https://github.com/form-data/form-data/commit/f4ca7f8e31f7e07df22c1aeb8e0a32a7055a64ca) +- Pass options to constructor if not used with new [`4bde68e`](https://github.com/form-data/form-data/commit/4bde68e12de1ba90fefad2e7e643f6375b902763) +- Make userHeaders optional [`2b4e478`](https://github.com/form-data/form-data/commit/2b4e4787031490942f2d1ee55c56b85a250875a7) + +## [v2.5.6](https://github.com/form-data/form-data/compare/v2.5.5...v2.5.6) - 2026-06-12 + +### Commits + +- [Fix] escape CR, LF, and `"` in field names and filenames [`b620316`](https://github.com/form-data/form-data/commit/b62031603c2d7c329b2a369b49466790f0ba6314) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `eslint`, `tape` [`12be578`](https://github.com/form-data/form-data/commit/12be578e936fd77eee75e2e656955f5343c4b80f) +- [Dev Deps] update `js-randomness-predictor` [`46cfd23`](https://github.com/form-data/form-data/commit/46cfd23bd40be14cfa0391e1c5357c4d74098f23) +- [Tests] use `safe-buffer` so the header-injection test runs on node < 4 [`633044a`](https://github.com/form-data/form-data/commit/633044a57a7b19f41cec2271ffd24afa2f6280af) +- [Deps] update `hasown` [`e3b96ee`](https://github.com/form-data/form-data/commit/e3b96eef1661bca8ea4297de057b78bf2734e900) + +## [v2.5.5](https://github.com/form-data/form-data/compare/v2.5.4...v2.5.5) - 2025-07-18 + +### Commits + +- [meta] actually ensure the readme backup isn’t published [`10626c0`](https://github.com/form-data/form-data/commit/10626c0a9b78c7d3fcaa51772265015ee0afc25c) +- [Fix] use proper dependency [`026abe5`](https://github.com/form-data/form-data/commit/026abe5c5c0489d8a2ccb59d5cfd14fb63078377) + +## [v2.5.4](https://github.com/form-data/form-data/compare/v2.5.3...v2.5.4) - 2025-07-17 + +### Fixed + +- [Fix] `append`: avoid a crash on nullish values [`#577`](https://github.com/form-data/form-data/issues/577) + +### Commits + +- [eslint] update linting config [`8bf2492`](https://github.com/form-data/form-data/commit/8bf2492e0555d41ff58fa04c91593af998f87a3c) +- [meta] add `auto-changelog` [`b5101ad`](https://github.com/form-data/form-data/commit/b5101ad3d5f73cfd0143aae3735b92826fd731ea) +- [Tests] handle predict-v8-randomness failures in node < 17 and node > 23 [`0e93122`](https://github.com/form-data/form-data/commit/0e93122358414942393d9c2dc434ae69e58be7c8) +- [Fix] Switch to using `crypto` random for boundary values [`b88316c`](https://github.com/form-data/form-data/commit/b88316c94bb004323669cd3639dc8bb8262539eb) +- [Fix] validate boundary type in `setBoundary()` method [`131ae5e`](https://github.com/form-data/form-data/commit/131ae5efa30b9c608add4faef3befb38aa2e1bf1) +- [Tests] Switch to newer v8 prediction library; enable node 24 testing [`c97cfbe`](https://github.com/form-data/form-data/commit/c97cfbed9eb6d2d4b5d53090f69ded4bf9fd8a21) +- [Refactor] use `hasown` [`97ac9c2`](https://github.com/form-data/form-data/commit/97ac9c208be0b83faeee04bb3faef1ed3474ee4c) +- [meta] remove local commit hooks [`be99d4e`](https://github.com/form-data/form-data/commit/be99d4eea5ce47139c23c1f0914596194019d7fb) +- [Dev Deps] remove unused deps [`ddbc89b`](https://github.com/form-data/form-data/commit/ddbc89b6d6d64f730bcb27cb33b7544068466a05) +- [meta] fix scripts to use prepublishOnly [`e351a97`](https://github.com/form-data/form-data/commit/e351a97e9f6c57c74ffd01625e83b09de805d08a) +- [Dev Deps] remove unused script [`8f23366`](https://github.com/form-data/form-data/commit/8f233664842da5bd605ce85541defc713d1d1e0a) +- [Dev Deps] add missing peer dep [`02ff026`](https://github.com/form-data/form-data/commit/02ff026fda71f9943cfdd5754727c628adb8d135) +- [meta] fix readme capitalization [`2fd5f61`](https://github.com/form-data/form-data/commit/2fd5f61ebfb526cd015fb8e7b8b8c1add4a38872) + +## [v2.5.3](https://github.com/form-data/form-data/compare/v2.5.2...v2.5.3) - 2025-02-14 + +### Merged + +- [Fix] set `Symbol.toStringTag` when available [`#573`](https://github.com/form-data/form-data/pull/573) + +### Fixed + +- [Fix] set `Symbol.toStringTag` when available (#573) [`#396`](https://github.com/form-data/form-data/issues/396) + +### Commits + +- [Refactor] use `Object.prototype.hasOwnProperty.call` [`6e682d4`](https://github.com/form-data/form-data/commit/6e682d4bd41de7e80de41e3c4ee10f23fcc3dd00) +- [Dev Deps] update `@types/node`, `browserify`, `coveralls`, `eslint`, `formidable`, `in-publish`, `phantomjs-prebuilt`, `pkgfiles`, `pre-commit`, `request`, `tape`, `typescript` [`819f6b7`](https://github.com/form-data/form-data/commit/819f6b7a543306a891fca37c3a06d0ff4a734422) +- Only apps should have lockfiles [`b170ee2`](https://github.com/form-data/form-data/commit/b170ee2b22b4c695c363b811c0c553d2fb1bbd79) +- [Deps] update `combined-stream`, `mime-types` [`6b1ca1d`](https://github.com/form-data/form-data/commit/6b1ca1dc7362a1b1c3a99a885516cca4b7eb817f) +- Bumped version 2.5.3 [`9457283`](https://github.com/form-data/form-data/commit/9457283e1dce6122adc908fdd7442cfc54cabe7a) +- [Dev Deps] pin `request` which via `tough-cookie` ^2.4 depends on `psl` [`9dbe192`](https://github.com/form-data/form-data/commit/9dbe192be3db215eac4d9c0b980470a5c2c030c6) + +## [v2.5.2](https://github.com/form-data/form-data/compare/v2.5.1...v2.5.2) - 2024-10-10 + +### Merged + +- fix (npmignore): ignore temporary build files [`#532`](https://github.com/form-data/form-data/pull/532) + +### Commits + +- [Tests] migrate from travis to GHA [`806eda7`](https://github.com/form-data/form-data/commit/806eda77740e6e3c67c7815afb216f2e1f187ba5) +- [eslint] clean up ignores [`3a9d480`](https://github.com/form-data/form-data/commit/3a9d480232dbcbc07260ad84c3da4975d9a3ae9e) +- [Fix] `Buffer.from` and `Buffer.alloc` require node 4+ [`c499f76`](https://github.com/form-data/form-data/commit/c499f76f1faac1ddbf210c45217038e4c1e02337) +- Bumped version 2.5.2 [`7020dd4`](https://github.com/form-data/form-data/commit/7020dd4c1260370abc40e86e3dfe49c5d576fbda) +- [Dev Deps] downgrade `cross-spawn` [`3fc1a9b`](https://github.com/form-data/form-data/commit/3fc1a9b62ddf1fe77a2bd6bd3476e4c0a9e01a88) +- fix: move util.isArray to Array.isArray (#564) [`10418d1`](https://github.com/form-data/form-data/commit/10418d1fe4b0d65fe020eafe3911feb5ad5e2bd6) + +## [v2.5.1](https://github.com/form-data/form-data/compare/v2.5.0...v2.5.1) - 2019-08-28 + +### Merged + +- Fix error in callback signatures [`#435`](https://github.com/form-data/form-data/pull/435) +- -Fixed: Eerror in the documentations as indicated in #439 [`#440`](https://github.com/form-data/form-data/pull/440) +- Add constructor options to TypeScript defs [`#437`](https://github.com/form-data/form-data/pull/437) + +### Commits + +- Add remaining combined-stream options to typedef [`4d41a32`](https://github.com/form-data/form-data/commit/4d41a32c0b3f85f8bbc9cf17df43befd2d5fc305) +- Bumped version 2.5.1 [`8ce81f5`](https://github.com/form-data/form-data/commit/8ce81f56cccf5466363a5eff135ad394a929f59b) +- Bump rimraf to 2.7.1 [`a6bc2d4`](https://github.com/form-data/form-data/commit/a6bc2d4296dbdee5d84cbab7c69bcd0eea7a12e2) + +## [v2.5.0](https://github.com/form-data/form-data/compare/v2.4.0...v2.5.0) - 2019-07-03 + +### Merged + +- - Added: public methods with information and examples to readme [`#429`](https://github.com/form-data/form-data/pull/429) +- chore: move @types/node to devDep [`#431`](https://github.com/form-data/form-data/pull/431) +- Switched windows tests from AppVeyor to Travis [`#430`](https://github.com/form-data/form-data/pull/430) +- feat(typings): migrate TS typings #427 [`#428`](https://github.com/form-data/form-data/pull/428) +- enhance the method of path.basename, handle undefined case [`#421`](https://github.com/form-data/form-data/pull/421) + +### Commits + +- - Added: public methods with information and examples to the readme file. [`21323f3`](https://github.com/form-data/form-data/commit/21323f3b4043a167046a4a2554c5f2825356c423) +- feat(typings): migrate TS typings [`a3c0142`](https://github.com/form-data/form-data/commit/a3c0142ed91b0c7dcaf89c4f618776708f1f70a9) +- - Fixed: Typos [`37350fa`](https://github.com/form-data/form-data/commit/37350fa250782f156a998ec1fa9671866d40ac49) +- Switched to Travis Windows from Appveyor [`fc61c73`](https://github.com/form-data/form-data/commit/fc61c7381fad12662df16dbc3e7621c91b886f03) +- - Fixed: rendering of subheaders [`e93ed8d`](https://github.com/form-data/form-data/commit/e93ed8df9d7f22078bc3a2c24889e9dfa11e192d) +- Updated deps and readme [`e3d8628`](https://github.com/form-data/form-data/commit/e3d8628728f6e4817ab97deeed92f0c822661b89) +- Updated dependencies [`19add50`](https://github.com/form-data/form-data/commit/19add50afb7de66c70d189f422d16f1b886616e2) +- Bumped version to 2.5.0 [`905f173`](https://github.com/form-data/form-data/commit/905f173a3f785e8d312998e765634ee451ca5f42) +- - Fixed: filesize is not a valid option? knownLength should be used for streams [`d88f912`](https://github.com/form-data/form-data/commit/d88f912b75b666b47f8674467516eade69d2d5be) +- Bump notion of modern node to node8 [`508b626`](https://github.com/form-data/form-data/commit/508b626bf1b460d3733d3420dc1cfd001617f6ac) +- enhance the method of path.basename [`faaa68a`](https://github.com/form-data/form-data/commit/faaa68a297be7d4fca0ac4709d5b93afc1f78b5c) + +## [v2.4.0](https://github.com/form-data/form-data/compare/v2.3.2...v2.4.0) - 2019-06-19 + +### Merged + +- Added "getBuffer" method and updated certificates [`#419`](https://github.com/form-data/form-data/pull/419) +- docs(readme): add axios integration document [`#425`](https://github.com/form-data/form-data/pull/425) +- Allow newer versions of combined-stream [`#402`](https://github.com/form-data/form-data/pull/402) + +### Commits + +- Updated: Certificate [`e90a76a`](https://github.com/form-data/form-data/commit/e90a76ab3dcaa63a6f3045f8255bfbb9c25a3e4e) +- Updated build/test/badges [`8512eef`](https://github.com/form-data/form-data/commit/8512eef436e28372f5bc88de3ca76a9cb46e6847) +- Bumped version 2.4.0 [`0f8da06`](https://github.com/form-data/form-data/commit/0f8da06c0b4c997bd2f6b09d78290d339616a950) +- docs(readme): remove unnecessary bracket [`4e3954d`](https://github.com/form-data/form-data/commit/4e3954dde304d27e3b95371d8c78002f3af5d5b2) +- Bumped version to 2.3.3 [`b16916a`](https://github.com/form-data/form-data/commit/b16916a568a0d06f3f8a16c31f9a8b89b7844094) + +## [v2.3.2](https://github.com/form-data/form-data/compare/v2.3.1...v2.3.2) - 2018-02-13 + +### Merged + +- Pulling in fixed combined-stream [`#379`](https://github.com/form-data/form-data/pull/379) + +### Commits + +- All the dev dependencies are breaking in old versions of node :'( [`c7dba6a`](https://github.com/form-data/form-data/commit/c7dba6a139d872d173454845e25e1850ed6b72b4) +- Updated badges [`19b6c7a`](https://github.com/form-data/form-data/commit/19b6c7a8a5c40f47f91c8a8da3e5e4dc3c449fa3) +- Try tests in node@4 [`872a326`](https://github.com/form-data/form-data/commit/872a326ab13e2740b660ff589b75232c3a85fcc9) +- Pull in final version [`9d44871`](https://github.com/form-data/form-data/commit/9d44871073d647995270b19dbc26f65671ce15c7) + +## [v2.3.1](https://github.com/form-data/form-data/compare/v2.3.0...v2.3.1) - 2017-08-24 + +### Commits + +- Updated readme with custom options example [`8e0a569`](https://github.com/form-data/form-data/commit/8e0a5697026016fe171e93bec43c2205279e23ca) +- Added support (tests) for node 8 [`d1d6f4a`](https://github.com/form-data/form-data/commit/d1d6f4ad4670d8ba84cc85b28e522ca0e93eb362) + +## [v2.3.0](https://github.com/form-data/form-data/compare/v2.2.0...v2.3.0) - 2017-08-24 + +### Merged + +- Added custom `options` support [`#368`](https://github.com/form-data/form-data/pull/368) +- Allow form.submit with url string param to use https [`#249`](https://github.com/form-data/form-data/pull/249) +- Proper header production [`#357`](https://github.com/form-data/form-data/pull/357) +- Fix wrong MIME type in example [`#285`](https://github.com/form-data/form-data/pull/285) + +### Commits + +- allow form.submit with url string param to use https [`c0390dc`](https://github.com/form-data/form-data/commit/c0390dcc623e15215308fa2bb0225aa431d9381e) +- update tests for url parsing [`eec0e80`](https://github.com/form-data/form-data/commit/eec0e807889d46697abd39a89ad9bf39996ba787) +- Uses for in to assign properties instead of Object.assign [`f6854ed`](https://github.com/form-data/form-data/commit/f6854edd85c708191bb9c89615a09fd0a9afe518) +- Adds test to check for option override [`61762f2`](https://github.com/form-data/form-data/commit/61762f2c5262e576d6a7f778b4ebab6546ef8582) +- Removes the 2mb maxDataSize limitation [`dc171c3`](https://github.com/form-data/form-data/commit/dc171c3ba49ac9b8813636fd4159d139b812315b) +- Ignore .DS_Store [`e8a05d3`](https://github.com/form-data/form-data/commit/e8a05d33361f7dca8927fe1d96433d049843de24) + +## [v2.2.0](https://github.com/form-data/form-data/compare/v2.1.4...v2.2.0) - 2017-06-11 + +### Merged + +- Filename can be a nested path [`#355`](https://github.com/form-data/form-data/pull/355) + +### Commits + +- Bumped version number. [`d7398c3`](https://github.com/form-data/form-data/commit/d7398c3e7cd81ed12ecc0b84363721bae467db02) + +## [v2.1.4](https://github.com/form-data/form-data/compare/2.1.3...v2.1.4) - 2017-04-08 + +## [2.1.3](https://github.com/form-data/form-data/compare/v2.1.3...2.1.3) - 2017-04-08 + +## [v2.1.3](https://github.com/form-data/form-data/compare/v2.1.2...v2.1.3) - 2017-04-08 + +### Merged + +- toString should output '[object FormData]' [`#346`](https://github.com/form-data/form-data/pull/346) + +## [v2.1.2](https://github.com/form-data/form-data/compare/v2.1.1...v2.1.2) - 2016-11-07 + +### Merged + +- #271 Added check for self and window objects + tests [`#282`](https://github.com/form-data/form-data/pull/282) + +### Commits + +- Added check for self and window objects + tests [`c99e4ec`](https://github.com/form-data/form-data/commit/c99e4ec32cd14d83776f2bdcc5a4e7384131c1b1) + +## [v2.1.1](https://github.com/form-data/form-data/compare/v2.1.0...v2.1.1) - 2016-10-03 + +### Merged + +- Bumped dependencies. [`#270`](https://github.com/form-data/form-data/pull/270) +- Update browser.js shim to use self instead of window [`#267`](https://github.com/form-data/form-data/pull/267) +- Boilerplate code rediction [`#265`](https://github.com/form-data/form-data/pull/265) +- eslint@3.7.0 [`#266`](https://github.com/form-data/form-data/pull/266) + +### Commits + +- code duplicates removed [`e9239fb`](https://github.com/form-data/form-data/commit/e9239fbe7d3c897b29fe3bde857d772469541c01) +- Changed according to requests [`aa99246`](https://github.com/form-data/form-data/commit/aa9924626bd9168334d73fea568c0ad9d8fbaa96) +- chore(package): update eslint to version 3.7.0 [`090a859`](https://github.com/form-data/form-data/commit/090a859835016cab0de49629140499e418db9c3a) + +## [v2.1.0](https://github.com/form-data/form-data/compare/v2.0.0...v2.1.0) - 2016-09-25 + +### Merged + +- Added `hasKnownLength` public method [`#263`](https://github.com/form-data/form-data/pull/263) + +### Commits + +- Added hasKnownLength public method [`655b959`](https://github.com/form-data/form-data/commit/655b95988ef2ed3399f8796b29b2a8673c1df11c) + +## [v2.0.0](https://github.com/form-data/form-data/compare/v1.0.0...v2.0.0) - 2016-09-16 + +### Merged + +- Replaced async with asynckit [`#258`](https://github.com/form-data/form-data/pull/258) +- Pre-release house cleaning [`#247`](https://github.com/form-data/form-data/pull/247) + +### Commits + +- Replaced async with asynckit. Modernized [`1749b78`](https://github.com/form-data/form-data/commit/1749b78d50580fbd080e65c1eb9702ad4f4fc0c0) +- Ignore .bak files [`c08190a`](https://github.com/form-data/form-data/commit/c08190a87d3e22a528b6e32b622193742a4c2672) +- Trying to be more chatty. :) [`c79eabb`](https://github.com/form-data/form-data/commit/c79eabb24eaf761069255a44abf4f540cfd47d40) + +## [v1.0.0](https://github.com/form-data/form-data/compare/v1.0.0-rc4...v1.0.0) - 2016-08-26 + +### Merged + +- Allow custom header fields to be set as an object. [`#190`](https://github.com/form-data/form-data/pull/190) +- v1.0.0-rc4 [`#182`](https://github.com/form-data/form-data/pull/182) +- Avoid undefined variable reference in older browsers [`#176`](https://github.com/form-data/form-data/pull/176) +- More housecleaning [`#164`](https://github.com/form-data/form-data/pull/164) +- More cleanup [`#159`](https://github.com/form-data/form-data/pull/159) +- Added windows testing. Some cleanup. [`#158`](https://github.com/form-data/form-data/pull/158) +- Housecleaning. Added test coverage. [`#156`](https://github.com/form-data/form-data/pull/156) +- Second iteration of cleanup. [`#145`](https://github.com/form-data/form-data/pull/145) + +### Commits + +- Pre-release house cleaning [`440d72b`](https://github.com/form-data/form-data/commit/440d72b5fd44dd132f42598c3183d46e5f35ce71) +- Updated deps, updated docs [`54b6114`](https://github.com/form-data/form-data/commit/54b61143e9ce66a656dd537a1e7b31319a4991be) +- make docs up-to-date [`5e383d7`](https://github.com/form-data/form-data/commit/5e383d7f1466713f7fcef58a6817e0cb466c8ba7) +- Added missing deps [`fe04862`](https://github.com/form-data/form-data/commit/fe04862000b2762245e2db69d5207696a08c1174) + +## [v1.0.0-rc4](https://github.com/form-data/form-data/compare/v1.0.0-rc3...v1.0.0-rc4) - 2016-03-15 + +### Merged + +- Housecleaning, preparing for the release [`#144`](https://github.com/form-data/form-data/pull/144) +- lib: emit error when failing to get length [`#127`](https://github.com/form-data/form-data/pull/127) +- Cleaning up for Codacity 2. [`#143`](https://github.com/form-data/form-data/pull/143) +- Cleaned up codacity concerns. [`#142`](https://github.com/form-data/form-data/pull/142) +- Should throw type error without new operator. [`#129`](https://github.com/form-data/form-data/pull/129) + +### Commits + +- More cleanup [`94b6565`](https://github.com/form-data/form-data/commit/94b6565bb98a387335c72feff5ed5c10da0a7f6f) +- Shuffling things around [`3c2f172`](https://github.com/form-data/form-data/commit/3c2f172eaddf0979b3eef5c73985d1a6fd3eee4a) +- Second iteration of cleanup. [`347c88e`](https://github.com/form-data/form-data/commit/347c88ef9a99a66b9bcf4278497425db2f0182b2) +- Housecleaning [`c335610`](https://github.com/form-data/form-data/commit/c3356100c054a4695e4dec8ed7072775cd745616) +- More housecleaning [`f573321`](https://github.com/form-data/form-data/commit/f573321824aae37ba2052a92cc889d533d9f8fb8) +- Trying to make far run on windows. + cleanup [`e426dfc`](https://github.com/form-data/form-data/commit/e426dfcefb07ee307d8a15dec04044cce62413e6) +- Playing with appveyor [`c9458a7`](https://github.com/form-data/form-data/commit/c9458a7c328782b19859bc1745e7d6b2005ede86) +- Updated dev dependencies. [`ceebe88`](https://github.com/form-data/form-data/commit/ceebe88872bb22da0a5a98daf384e3cc232928d3) +- Replaced win-spawn with cross-spawn [`405a69e`](https://github.com/form-data/form-data/commit/405a69ee34e235ee6561b5ff0140b561be40d1cc) +- Updated readme badges. [`12f282a`](https://github.com/form-data/form-data/commit/12f282a1310fcc2f70cc5669782283929c32a63d) +- Making paths windows friendly. [`f4bddc5`](https://github.com/form-data/form-data/commit/f4bddc5955e2472f8e23c892c9b4d7a08fcb85a3) +- [WIP] trying things for greater sanity [`8ad1f02`](https://github.com/form-data/form-data/commit/8ad1f02b0b3db4a0b00c5d6145ed69bcb7558213) +- Bending under Codacy [`bfff3bb`](https://github.com/form-data/form-data/commit/bfff3bb36052dc83f429949b4e6f9b146a49d996) +- Another attempt to make windows friendly [`f3eb628`](https://github.com/form-data/form-data/commit/f3eb628974ccb91ba0020f41df490207eeed77f6) +- Updated dependencies. [`f73996e`](https://github.com/form-data/form-data/commit/f73996e0508ee2d4b2b376276adfac1de4188ac2) +- Missed travis changes. [`67ee79f`](https://github.com/form-data/form-data/commit/67ee79f964fdabaf300bd41b0af0c1cfaca07687) +- Restructured badges. [`48444a1`](https://github.com/form-data/form-data/commit/48444a1ff156ba2c2c3cfd11047c2f2fd92d4474) +- Add similar type error as the browser for attempting to use form-data without new. [`5711320`](https://github.com/form-data/form-data/commit/5711320fb7c8cc620cfc79b24c7721526e23e539) +- Took out codeclimate-test-reporter [`a7e0c65`](https://github.com/form-data/form-data/commit/a7e0c6522afe85ca9974b0b4e1fca9c77c3e52b1) +- One more [`8e84cff`](https://github.com/form-data/form-data/commit/8e84cff3370526ecd3e175fd98e966242d81993c) + +## [v1.0.0-rc3](https://github.com/form-data/form-data/compare/v1.0.0-rc2...v1.0.0-rc3) - 2015-07-29 + +### Merged + +- House cleaning. Added `pre-commit`. [`#140`](https://github.com/form-data/form-data/pull/140) +- Allow custom content-type without setting a filename. [`#138`](https://github.com/form-data/form-data/pull/138) +- Add node-fetch to alternative submission methods. [`#132`](https://github.com/form-data/form-data/pull/132) +- Update dependencies [`#130`](https://github.com/form-data/form-data/pull/130) +- Switching to container based TravisCI [`#136`](https://github.com/form-data/form-data/pull/136) +- Default content-type to 'application/octect-stream' [`#128`](https://github.com/form-data/form-data/pull/128) +- Allow filename as third option of .append [`#125`](https://github.com/form-data/form-data/pull/125) + +### Commits + +- Allow custom content-type without setting a filename [`c8a77cc`](https://github.com/form-data/form-data/commit/c8a77cc0cf16d15f1ebf25272beaab639ce89f76) +- Fixed ranged test. [`a5ac58c`](https://github.com/form-data/form-data/commit/a5ac58cbafd0909f32fe8301998f689314fd4859) +- Allow filename as third option of #append [`d081005`](https://github.com/form-data/form-data/commit/d0810058c84764b3c463a18b15ebb37864de9260) +- Allow custom content-type without setting a filename [`8cb9709`](https://github.com/form-data/form-data/commit/8cb9709e5f1809cfde0cd707dbabf277138cd771) + +## [v1.0.0-rc2](https://github.com/form-data/form-data/compare/v1.0.0-rc1...v1.0.0-rc2) - 2015-07-21 + +### Merged + +- #109 Append proper line break [`#123`](https://github.com/form-data/form-data/pull/123) +- Add shim for browser (browserify/webpack). [`#122`](https://github.com/form-data/form-data/pull/122) +- Update license field [`#115`](https://github.com/form-data/form-data/pull/115) + +### Commits + +- Add shim for browser. [`87c33f4`](https://github.com/form-data/form-data/commit/87c33f4269a2211938f80ab3e53835362b1afee8) +- Bump version [`a3f5d88`](https://github.com/form-data/form-data/commit/a3f5d8872c810ce240c7d3838c69c3c9fcecc111) + +## [v1.0.0-rc1](https://github.com/form-data/form-data/compare/0.2...v1.0.0-rc1) - 2015-06-13 + +### Merged + +- v1.0.0-rc1 [`#114`](https://github.com/form-data/form-data/pull/114) +- Updated test targets [`#102`](https://github.com/form-data/form-data/pull/102) +- Remove duplicate plus sign [`#94`](https://github.com/form-data/form-data/pull/94) + +### Commits + +- Made https test local. Updated deps. [`afe1959`](https://github.com/form-data/form-data/commit/afe1959ec711f23e57038ab5cb20fedd86271f29) +- Proper self-signed ssl [`4d5ec50`](https://github.com/form-data/form-data/commit/4d5ec50e81109ad2addf3dbb56dc7c134df5ff87) +- Update HTTPS handling for modern days [`2c11b01`](https://github.com/form-data/form-data/commit/2c11b01ce2c06e205c84d7154fa2f27b66c94f3b) +- Made tests more local [`09633fa`](https://github.com/form-data/form-data/commit/09633fa249e7ce3ac581543aafe16ee9039a823b) +- Auto create tmp folder for Formidable [`28714b7`](https://github.com/form-data/form-data/commit/28714b7f71ad556064cdff88fabe6b92bd407ddd) +- remove duplicate plus sign [`36e09c6`](https://github.com/form-data/form-data/commit/36e09c695b0514d91a23f5cd64e6805404776fc7) + +## [0.2](https://github.com/form-data/form-data/compare/0.1.4...0.2) - 2014-12-06 + +### Merged + +- Bumped version [`#96`](https://github.com/form-data/form-data/pull/96) +- Replace mime library. [`#95`](https://github.com/form-data/form-data/pull/95) +- #71 Respect bytes range in a read stream. [`#73`](https://github.com/form-data/form-data/pull/73) + +## [0.1.4](https://github.com/form-data/form-data/compare/0.1.3...0.1.4) - 2014-06-23 + +### Merged + +- Updated version. [`#76`](https://github.com/form-data/form-data/pull/76) +- #71 Respect bytes range in a read stream. [`#75`](https://github.com/form-data/form-data/pull/75) + +## [0.1.3](https://github.com/form-data/form-data/compare/0.1.2...0.1.3) - 2014-06-17 + +### Merged + +- Updated versions. [`#69`](https://github.com/form-data/form-data/pull/69) +- Added custom headers support [`#60`](https://github.com/form-data/form-data/pull/60) +- Added test for Request. Small fixes. [`#56`](https://github.com/form-data/form-data/pull/56) + +### Commits + +- Added test for the custom header functionality [`bd50685`](https://github.com/form-data/form-data/commit/bd506855af62daf728ef1718cae88ed23bb732f3) +- Documented custom headers option [`77a024a`](https://github.com/form-data/form-data/commit/77a024a9375f93c246c35513d80f37d5e11d35ff) +- Removed 0.6 support. [`aee8dce`](https://github.com/form-data/form-data/commit/aee8dce604c595cfaacfc6efb12453d1691ac0d6) + +## [0.1.2](https://github.com/form-data/form-data/compare/0.1.1...0.1.2) - 2013-10-02 + +### Merged + +- Fixed default https port assignment, added tests. [`#52`](https://github.com/form-data/form-data/pull/52) +- #45 Added tests for multi-submit. Updated readme. [`#49`](https://github.com/form-data/form-data/pull/49) +- #47 return request from .submit() [`#48`](https://github.com/form-data/form-data/pull/48) + +### Commits + +- Bumped version. [`2b761b2`](https://github.com/form-data/form-data/commit/2b761b256ae607fc2121621f12c2e1042be26baf) + +## [0.1.1](https://github.com/form-data/form-data/compare/0.1.0...0.1.1) - 2013-08-21 + +### Merged + +- Added license type and reference to package.json [`#46`](https://github.com/form-data/form-data/pull/46) + +### Commits + +- #47 return request from .submit() [`1d61c2d`](https://github.com/form-data/form-data/commit/1d61c2da518bd5e136550faa3b5235bb540f1e06) +- #47 Updated readme. [`e3dae15`](https://github.com/form-data/form-data/commit/e3dae1526bd3c3b9d7aff6075abdaac12c3cc60f) + +## [0.1.0](https://github.com/form-data/form-data/compare/0.0.10...0.1.0) - 2013-07-08 + +### Merged + +- Update master to 0.1.0 [`#44`](https://github.com/form-data/form-data/pull/44) +- 0.1.0 - Added error handling. Streamlined edge cases behavior. [`#43`](https://github.com/form-data/form-data/pull/43) +- Pointed badges back to mothership. [`#39`](https://github.com/form-data/form-data/pull/39) +- Updated node-fake to support 0.11 tests. [`#37`](https://github.com/form-data/form-data/pull/37) +- Updated tests to play nice with 0.10 [`#36`](https://github.com/form-data/form-data/pull/36) +- #32 Added .npmignore [`#34`](https://github.com/form-data/form-data/pull/34) +- Spring cleaning [`#30`](https://github.com/form-data/form-data/pull/30) + +### Commits + +- Added error handling. Streamlined edge cases behavior. [`4da496e`](https://github.com/form-data/form-data/commit/4da496e577cb9bc0fd6c94cbf9333a0082ce353a) +- Made tests more deterministic. [`7fc009b`](https://github.com/form-data/form-data/commit/7fc009b8a2cc9232514a44b2808b9f89ce68f7d2) +- Fixed styling. [`d373b41`](https://github.com/form-data/form-data/commit/d373b417e779024bc3326073e176383cd08c0b18) +- #40 Updated Readme.md regarding getLengthSync() [`efb373f`](https://github.com/form-data/form-data/commit/efb373fd63814d977960e0299d23c92cd876cfef) +- Updated readme. [`527e3a6`](https://github.com/form-data/form-data/commit/527e3a63b032cb6f576f597ad7ff2ebcf8a0b9b4) + +## [0.0.10](https://github.com/form-data/form-data/compare/0.0.9...0.0.10) - 2013-05-08 + +### Commits + +- Updated tests to play nice with 0.10. [`932b39b`](https://github.com/form-data/form-data/commit/932b39b773e49edcb2c5d2e58fe389ab6c42f47c) +- Added dependency tracking. [`3131d7f`](https://github.com/form-data/form-data/commit/3131d7f6996cd519d50547e4de1587fd80d0fa07) + +## 0.0.9 - 2013-04-29 + +### Merged + +- Custom params for form.submit() should cover most edge cases. [`#22`](https://github.com/form-data/form-data/pull/22) +- Updated Readme and version number. [`#20`](https://github.com/form-data/form-data/pull/20) +- Allow custom headers and pre-known length in parts [`#17`](https://github.com/form-data/form-data/pull/17) +- Bumped version number. [`#12`](https://github.com/form-data/form-data/pull/12) +- Fix for #10 [`#11`](https://github.com/form-data/form-data/pull/11) +- Bumped version number. [`#8`](https://github.com/form-data/form-data/pull/8) +- Added support for https destination, http-response and mikeal's request streams. [`#7`](https://github.com/form-data/form-data/pull/7) +- Updated git url. [`#6`](https://github.com/form-data/form-data/pull/6) +- Version bump. [`#5`](https://github.com/form-data/form-data/pull/5) +- Changes to support custom content-type and getLengthSync. [`#4`](https://github.com/form-data/form-data/pull/4) +- make .submit(url) use host from url, not 'localhost' [`#2`](https://github.com/form-data/form-data/pull/2) +- Make package.json JSON [`#1`](https://github.com/form-data/form-data/pull/1) + +### Fixed + +- Add MIT license [`#14`](https://github.com/form-data/form-data/issues/14) + +### Commits + +- Spring cleaning. [`850ba1b`](https://github.com/form-data/form-data/commit/850ba1b649b6856b0fa87bbcb04bc70ece0137a6) +- Added custom request params to form.submit(). Made tests more stable. [`de3502f`](https://github.com/form-data/form-data/commit/de3502f6c4a509f6ed12a7dd9dc2ce9c2e0a8d23) +- Basic form (no files) working [`6ffdc34`](https://github.com/form-data/form-data/commit/6ffdc343e8594cfc2efe1e27653ea39d8980a14e) +- Got initial test to pass [`9a59d08`](https://github.com/form-data/form-data/commit/9a59d08c024479fd3c9d99ba2f0893a47b3980f0) +- Implement initial getLength [`9060c91`](https://github.com/form-data/form-data/commit/9060c91b861a6573b73beddd11e866db422b5830) +- Make getLength work with file streams [`6f6b1e9`](https://github.com/form-data/form-data/commit/6f6b1e9b65951e6314167db33b446351702f5558) +- Implemented a simplistic submit() function [`41e9cc1`](https://github.com/form-data/form-data/commit/41e9cc124124721e53bc1d1459d45db1410c44e6) +- added test for custom headers and content-length in parts (felixge/node-form-data/17) [`b16d14e`](https://github.com/form-data/form-data/commit/b16d14e693670f5d52babec32cdedd1aa07c1aa4) +- Fixed code styling. [`5847424`](https://github.com/form-data/form-data/commit/5847424c666970fc2060acd619e8a78678888a82) +- #29 Added custom filename and content-type options to support identity-less streams. [`adf8b4a`](https://github.com/form-data/form-data/commit/adf8b4a41530795682cd3e35ffaf26b30288ccda) +- Initial Readme and package.json [`8c744e5`](https://github.com/form-data/form-data/commit/8c744e58be4014bdf432e11b718ed87f03e217af) +- allow append() to completely override header and boundary [`3fb2ad4`](https://github.com/form-data/form-data/commit/3fb2ad491f66e4b4ff16130be25b462820b8c972) +- Syntax highlighting [`ab3a6a5`](https://github.com/form-data/form-data/commit/ab3a6a5ed1ab77a2943ce3befcb2bb3cd9ff0330) +- Updated Readme.md [`de8f441`](https://github.com/form-data/form-data/commit/de8f44122ca754cbfedc0d2748e84add5ff0b669) +- Added examples to Readme file. [`c406ac9`](https://github.com/form-data/form-data/commit/c406ac921d299cbc130464ed19338a9ef97cb650) +- pass options.knownLength to set length at beginning, w/o waiting for async size calculation [`e2ac039`](https://github.com/form-data/form-data/commit/e2ac0397ff7c37c3dca74fa9925b55f832e4fa0b) +- Updated dependencies and added test command. [`09bd7cd`](https://github.com/form-data/form-data/commit/09bd7cd86f1ad7a58df1b135eb6eef0d290894b4) +- Bumped version. Updated readme. [`4581140`](https://github.com/form-data/form-data/commit/4581140f322758c6fc92019d342c7d7d6c94af5c) +- Test runner [`1707ebb`](https://github.com/form-data/form-data/commit/1707ebbd180856e6ed44e80c46b02557e2425762) +- Added .npmignore, bumped version. [`2e033e0`](https://github.com/form-data/form-data/commit/2e033e0e4be7c1457be090cd9b2996f19d8fb665) +- FormData.prototype.append takes and passes along options (for header) [`b519203`](https://github.com/form-data/form-data/commit/b51920387ed4da7b4e106fc07b9459f26b5ae2f0) +- Make package.json JSON [`bf1b58d`](https://github.com/form-data/form-data/commit/bf1b58df794b10fda86ed013eb9237b1e5032085) +- Add dependencies to package.json [`7413d0b`](https://github.com/form-data/form-data/commit/7413d0b4cf5546312d47ea426db8180619083974) +- Add convenient submit() interface [`55855e4`](https://github.com/form-data/form-data/commit/55855e4bea14585d4a3faf9e7318a56696adbc7d) +- Fix content type [`08b6ae3`](https://github.com/form-data/form-data/commit/08b6ae337b23ef1ba457ead72c9b133047df213c) +- Combatting travis rvm calls. [`409adfd`](https://github.com/form-data/form-data/commit/409adfd100a3cf4968a632c05ba58d92d262d144) +- Fixed Issue #2 [`b3a5d66`](https://github.com/form-data/form-data/commit/b3a5d661739dcd6921b444b81d5cb3c32fab655d) +- Fix for #10. [`bab70b9`](https://github.com/form-data/form-data/commit/bab70b9e803e17287632762073d227d6c59989e0) +- Trying workarounds for formidable - 0.6 "love". [`25782a3`](https://github.com/form-data/form-data/commit/25782a3f183d9c30668ec2bca6247ed83f10611c) +- change whitespace to conform with felixge's style guide [`9fa34f4`](https://github.com/form-data/form-data/commit/9fa34f433bece85ef73086a874c6f0164ab7f1f6) +- Add async to deps [`b7d1a6b`](https://github.com/form-data/form-data/commit/b7d1a6b10ee74be831de24ed76843e5a6935f155) +- typo [`7860a9c`](https://github.com/form-data/form-data/commit/7860a9c8a582f0745ce0e4a0549f4bffc29c0b50) +- Bumped version. [`fa36c1b`](https://github.com/form-data/form-data/commit/fa36c1b4229c34b85d7efd41908429b6d1da3bfc) +- Updated .gitignore [`de567bd`](https://github.com/form-data/form-data/commit/de567bde620e53b8e9b0ed3506e79491525ec558) +- Don't rely on resume() being called by pipe [`1deae47`](https://github.com/form-data/form-data/commit/1deae47e042bcd170bd5dbe2b4a4fa5356bb8aa2) +- One more wrong content type [`28f166d`](https://github.com/form-data/form-data/commit/28f166d443e2eb77f2559324014670674b97e46e) +- Another typo [`b959b6a`](https://github.com/form-data/form-data/commit/b959b6a2be061cac17f8d329b89cea109f0f32be) +- Typo [`698fa0a`](https://github.com/form-data/form-data/commit/698fa0aa5dbf4eeb77377415acc202a6fbe3f4a2) +- Being simply dumb. [`b614db8`](https://github.com/form-data/form-data/commit/b614db85702061149fbd98418605106975e72ade) +- Fixed typo in the filename. [`30af6be`](https://github.com/form-data/form-data/commit/30af6be13fb0c9e92b32e935317680b9d7599928) diff --git a/node_modules/form-data/License b/node_modules/form-data/License new file mode 100644 index 0000000000000000000000000000000000000000..c7ff12a2f8af2e2c57f39da1754409c25b35f46a --- /dev/null +++ b/node_modules/form-data/License @@ -0,0 +1,19 @@ +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/node_modules/form-data/README.md b/node_modules/form-data/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d71caea3d301db3967e9b5fadbc118d0ea0a4279 --- /dev/null +++ b/node_modules/form-data/README.md @@ -0,0 +1,355 @@ +# Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data) + +A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications. + +The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd]. + +[xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface + +[![Linux Build](https://img.shields.io/travis/form-data/form-data/v4.0.6.svg?label=linux:6.x-12.x)](https://travis-ci.org/form-data/form-data) +[![MacOS Build](https://img.shields.io/travis/form-data/form-data/v4.0.6.svg?label=macos:6.x-12.x)](https://travis-ci.org/form-data/form-data) +[![Windows Build](https://img.shields.io/travis/form-data/form-data/v4.0.6.svg?label=windows:6.x-12.x)](https://travis-ci.org/form-data/form-data) + +[![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/v4.0.6.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master) +[![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data) + +## Install + +``` +npm install --save form-data +``` + +## Usage + +In this example we are constructing a form with 3 fields that contain a string, +a buffer and a file stream. + +``` javascript +var FormData = require('form-data'); +var fs = require('fs'); + +var form = new FormData(); +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_file', fs.createReadStream('/foo/bar.jpg')); +``` + +Also you can use http-response stream: + +``` javascript +var FormData = require('form-data'); +var http = require('http'); + +var form = new FormData(); + +http.request('http://nodejs.org/images/logo.png', function (response) { + form.append('my_field', 'my value'); + form.append('my_buffer', new Buffer(10)); + form.append('my_logo', response); +}); +``` + +Or @mikeal's [request](https://github.com/request/request) stream: + +``` javascript +var FormData = require('form-data'); +var request = require('request'); + +var form = new FormData(); + +form.append('my_field', 'my value'); +form.append('my_buffer', new Buffer(10)); +form.append('my_logo', request('http://nodejs.org/images/logo.png')); +``` + +In order to submit this form to a web application, call ```submit(url, [callback])``` method: + +``` javascript +form.submit('http://example.org/', function (err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +}); + +``` + +For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods. + +### Custom options + +You can provide custom options, such as `maxDataSize`: + +``` javascript +var FormData = require('form-data'); + +var form = new FormData({ maxDataSize: 20971520 }); +form.append('my_field', 'my value'); +form.append('my_buffer', /* something big */); +``` + +List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15) + +### Alternative submission methods + +You can use node's http client interface: + +``` javascript +var http = require('http'); + +var request = http.request({ + method: 'post', + host: 'example.org', + path: '/upload', + headers: form.getHeaders() +}); + +form.pipe(request); + +request.on('response', function (res) { + console.log(res.statusCode); +}); +``` + +Or if you would prefer the `'Content-Length'` header to be set for you: + +``` javascript +form.submit('example.org/upload', function (err, res) { + console.log(res.statusCode); +}); +``` + +To use custom headers and pre-known length in parts: + +``` javascript +var CRLF = '\r\n'; +var form = new FormData(); + +var options = { + header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, + knownLength: 1 +}; + +form.append('my_buffer', buffer, options); + +form.submit('http://example.com/', function (err, res) { + if (err) throw err; + console.log('Done'); +}); +``` + +Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually: + +``` javascript +someModule.stream(function (err, stdout, stderr) { + if (err) throw err; + + var form = new FormData(); + + form.append('file', stdout, { + filename: 'unicycle.jpg', // ... or: + filepath: 'photos/toys/unicycle.jpg', + contentType: 'image/jpeg', + knownLength: 19806 + }); + + form.submit('http://example.com/', function (err, res) { + if (err) throw err; + console.log('Done'); + }); +}); +``` + +The `filepath` property overrides `filename` and may contain a relative path. This is typically used when uploading [multiple files from a directory](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory). + +For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter: + +``` javascript +form.submit({ + host: 'example.com', + path: '/probably.php?extra=params', + auth: 'username:password' +}, function (err, res) { + console.log(res.statusCode); +}); +``` + +In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`: + +``` javascript +form.submit({ + host: 'example.com', + path: '/surelynot.php', + headers: { 'x-test-header': 'test-header-value' } +}, function (err, res) { + console.log(res.statusCode); +}); +``` + +### Methods + +- [_Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] )](https://github.com/form-data/form-data#void-append-string-field-mixed-value--mixed-options-). +- [_Headers_ getHeaders( [**Headers** _userHeaders_] )](https://github.com/form-data/form-data#array-getheaders-array-userheaders-) +- [_String_ getBoundary()](https://github.com/form-data/form-data#string-getboundary) +- [_Void_ setBoundary()](https://github.com/form-data/form-data#void-setboundary) +- [_Buffer_ getBuffer()](https://github.com/form-data/form-data#buffer-getbuffer) +- [_Integer_ getLengthSync()](https://github.com/form-data/form-data#integer-getlengthsync) +- [_Integer_ getLength( **function** _callback_ )](https://github.com/form-data/form-data#integer-getlength-function-callback-) +- [_Boolean_ hasKnownLength()](https://github.com/form-data/form-data#boolean-hasknownlength) +- [_Request_ submit( _params_, **function** _callback_ )](https://github.com/form-data/form-data#request-submit-params-function-callback-) +- [_String_ toString()](https://github.com/form-data/form-data#string-tostring) + +#### _Void_ append( **String** _field_, **Mixed** _value_ [, **Mixed** _options_] ) +Append data to the form. You can submit about any format (string, integer, boolean, buffer, etc.). However, Arrays are not supported and need to be turned into strings by the user. +```javascript +var form = new FormData(); +form.append('my_string', 'my value'); +form.append('my_integer', 1); +form.append('my_boolean', true); +form.append('my_buffer', new Buffer(10)); +form.append('my_array_as_json', JSON.stringify(['bird', 'cute'])); +``` + +You may provide a string for options, or an object. +```javascript +// Set filename by providing a string for options +form.append('my_file', fs.createReadStream('/foo/bar.jpg'), 'bar.jpg'); + +// provide an object. +form.append('my_file', fs.createReadStream('/foo/bar.jpg'), { filename: 'bar.jpg', contentType: 'image/jpeg', knownLength: 19806 }); +``` + +#### _Headers_ getHeaders( [**Headers** _userHeaders_] ) +This method adds the correct `content-type` header to the provided array of `userHeaders`. + +#### _String_ getBoundary() +Return the boundary of the formData. By default, the boundary consists of 26 `-` followed by 24 numbers +for example: +```javascript +--------------------------515890814546601021194782 +``` + +#### _Void_ setBoundary(String _boundary_) +Set the boundary string, overriding the default behavior described above. + +_Note: The boundary must be unique and may not appear in the data._ + +#### _Buffer_ getBuffer() +Return the full formdata request package, as a Buffer. You can insert this Buffer in e.g. Axios to send multipart data. +```javascript +var form = new FormData(); +form.append('my_buffer', Buffer.from([0x4a,0x42,0x20,0x52,0x6f,0x63,0x6b,0x73])); +form.append('my_file', fs.readFileSync('/foo/bar.jpg')); + +axios.post('https://example.com/path/to/api', form.getBuffer(), form.getHeaders()); +``` +**Note:** Because the output is of type Buffer, you can only append types that are accepted by Buffer: *string, Buffer, ArrayBuffer, Array, or Array-like Object*. A ReadStream for example will result in an error. + +#### _Integer_ getLengthSync() +Same as `getLength` but synchronous. + +_Note: getLengthSync __doesn't__ calculate streams length._ + +#### _Integer_ getLength(**function** _callback_ ) +Returns the `Content-Length` async. The callback is used to handle errors and continue once the length has been calculated +```javascript +this.getLength(function (err, length) { + if (err) { + this._error(err); + return; + } + + // add content length + request.setHeader('Content-Length', length); + + ... +}.bind(this)); +``` + +#### _Boolean_ hasKnownLength() +Checks if the length of added values is known. + +#### _Request_ submit(_params_, **function** _callback_ ) +Submit the form to a web application. +```javascript +var form = new FormData(); +form.append('my_string', 'Hello World'); + +form.submit('http://example.com/', function (err, res) { + // res – response object (http.IncomingMessage) // + res.resume(); +} ); +``` + +#### _String_ toString() +Returns the form data as a string. Don't use this if you are sending files or buffers, use `getBuffer()` instead. + +### Integration with other libraries + +#### Request + +Form submission using [request](https://github.com/request/request): + +```javascript +var formData = { + my_field: 'my_value', + my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), +}; + +request.post({url:'http://service.com/upload', formData: formData}, function (err, httpResponse, body) { + if (err) { + return console.error('upload failed:', err); + } + console.log('Upload successful! Server responded with:', body); +}); +``` + +For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads). + +#### node-fetch + +You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch): + +```javascript +var form = new FormData(); + +form.append('a', 1); + +fetch('http://example.com', { method: 'POST', body: form }) + .then(function (res) { + return res.json(); + }).then(function (json) { + console.log(json); + }); +``` + +#### axios + +In Node.js you can post a file using [axios](https://github.com/axios/axios): +```javascript +const form = new FormData(); +const stream = fs.createReadStream(PATH_TO_FILE); + +form.append('image', stream); + +// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders` +const formHeaders = form.getHeaders(); + +axios.post('http://example.com', form, { + headers: { + ...formHeaders, + }, +}) + .then(response => response) + .catch(error => error) +``` + +## Notes + +- ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround. +- ```getLength(cb)``` will send an error as first parameter of callback if stream length cannot be calculated (e.g. send in custom streams w/o using ```knownLength```). +- ```submit``` will not add `content-length` if form length is unknown or not calculable. +- Starting version `2.x` FormData has dropped support for `node@0.10.x`. +- Starting version `3.x` FormData has dropped support for `node@4.x`. + +## License + +Form-Data is released under the [MIT](License) license. diff --git a/node_modules/form-data/index.d.ts b/node_modules/form-data/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..295e9e9bc5fb9a2c1667c0dcd23876b263ee7903 --- /dev/null +++ b/node_modules/form-data/index.d.ts @@ -0,0 +1,62 @@ +// Definitions by: Carlos Ballesteros Velasco +// Leon Yu +// BendingBender +// Maple Miao + +/// +import * as stream from 'stream'; +import * as http from 'http'; + +export = FormData; + +// Extracted because @types/node doesn't export interfaces. +interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: stream.Readable, size: number): void; + destroy?(this: stream.Readable, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean; +} + +interface Options extends ReadableOptions { + writable?: boolean; + readable?: boolean; + dataSize?: number; + maxDataSize?: number; + pauseStreams?: boolean; +} + +declare class FormData extends stream.Readable { + constructor(options?: Options); + append(key: string, value: any, options?: FormData.AppendOptions | string): void; + getHeaders(userHeaders?: FormData.Headers): FormData.Headers; + submit( + params: string | FormData.SubmitOptions, + callback?: (error: Error | null, response: http.IncomingMessage) => void + ): http.ClientRequest; + getBuffer(): Buffer; + setBoundary(boundary: string): void; + getBoundary(): string; + getLength(callback: (err: Error | null, length: number) => void): void; + getLengthSync(): number; + hasKnownLength(): boolean; +} + +declare namespace FormData { + interface Headers { + [key: string]: any; + } + + interface AppendOptions { + header?: string | Headers; + knownLength?: number; + filename?: string; + filepath?: string; + contentType?: string; + } + + interface SubmitOptions extends http.RequestOptions { + protocol?: 'https:' | 'http:'; + } +} diff --git a/node_modules/form-data/lib/browser.js b/node_modules/form-data/lib/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..8950a913aefa2b526c2b4a0ef949d364dfeb72c3 --- /dev/null +++ b/node_modules/form-data/lib/browser.js @@ -0,0 +1,4 @@ +'use strict'; + +/* eslint-env browser */ +module.exports = typeof self === 'object' ? self.FormData : window.FormData; diff --git a/node_modules/form-data/lib/form_data.js b/node_modules/form-data/lib/form_data.js new file mode 100644 index 0000000000000000000000000000000000000000..a05c8ce8c2bdff8a9aea43f0a117e5f9a283c09d --- /dev/null +++ b/node_modules/form-data/lib/form_data.js @@ -0,0 +1,506 @@ +'use strict'; + +var CombinedStream = require('combined-stream'); +var util = require('util'); +var path = require('path'); +var http = require('http'); +var https = require('https'); +var parseUrl = require('url').parse; +var fs = require('fs'); +var Stream = require('stream').Stream; +var crypto = require('crypto'); +var mime = require('mime-types'); +var asynckit = require('asynckit'); +var setToStringTag = require('es-set-tostringtag'); +var hasOwn = require('hasown'); +var populate = require('./populate.js'); + +/** + * Escape CR, LF, and `"` in a multipart `name`/`filename` parameter, so a field + * name or filename can not break out of its header line to inject headers or + * smuggle additional parts. Matches the WHATWG HTML multipart/form-data encoding. + * + * @param {string} str - the parameter value to escape + * @returns {string} the escaped value + */ +function escapeHeaderParam(str) { + return String(str).replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22'); +} + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); + } + + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + + CombinedStream.call(this); + + options = options || {}; // eslint-disable-line no-param-reassign + for (var option in options) { // eslint-disable-line no-restricted-syntax + this[option] = options[option]; + } +} + +// make it a Stream +util.inherits(FormData, CombinedStream); + +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; + +FormData.prototype.append = function (field, value, options) { + options = options || {}; // eslint-disable-line no-param-reassign + + // allow filename as single option + if (typeof options === 'string') { + options = { filename: options }; // eslint-disable-line no-param-reassign + } + + var append = CombinedStream.prototype.append.bind(this); + + // all that streamy business can't handle numbers + if (typeof value === 'number' || value == null) { + value = String(value); // eslint-disable-line no-param-reassign + } + + // https://github.com/felixge/node-form-data/issues/38 + if (Array.isArray(value)) { + /* + * Please convert your array into string + * the way web server expects it + */ + this._error(new Error('Arrays are not supported.')); + return; + } + + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + + append(header); + append(value); + append(footer); + + // pass along options.knownLength + this._trackLength(header, value, options); +}; + +FormData.prototype._trackLength = function (header, value, options) { + var valueLength = 0; + + /* + * used w/ getLengthSync(), when length is known. + * e.g. for streaming directly from a remote server, + * w/ a known file a size, and not wanting to wait for + * incoming file to finish to get its size. + */ + if (options.knownLength != null) { + valueLength += Number(options.knownLength); + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } + + this._valueLength += valueLength; + + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += Buffer.byteLength(header) + FormData.LINE_BREAK.length; + + // empty or either doesn't have path or not an http response or not a stream + if (!value || (!value.path && !(value.readable && hasOwn(value, 'httpVersion')) && !(value instanceof Stream))) { + return; + } + + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; + +FormData.prototype._lengthRetriever = function (value, callback) { + if (hasOwn(value, 'fd')) { + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); // eslint-disable-line callback-return + + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function (err, stat) { + if (err) { + callback(err); + return; + } + + // update final size based on the range options + var fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } + + // or http response + } else if (hasOwn(value, 'httpVersion')) { + callback(null, Number(value.headers['content-length'])); // eslint-disable-line callback-return + + // or request stream http://github.com/mikeal/request + } else if (hasOwn(value, 'httpModule')) { + // wait till response come back + value.on('response', function (response) { + value.pause(); + callback(null, Number(response.headers['content-length'])); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); // eslint-disable-line callback-return + } +}; + +FormData.prototype._multiPartHeader = function (field, value, options) { + /* + * custom header specified (as string)? + * it becomes responsible for boundary + * (e.g. to handle extra CRLFs on .NET servers) + */ + if (typeof options.header === 'string') { + return options.header; + } + + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + escapeHeaderParam(field) + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; + + // allow custom headers. + if (typeof options.header === 'object') { + populate(headers, options.header); + } + + var header; + for (var prop in headers) { // eslint-disable-line no-restricted-syntax + if (hasOwn(headers, prop)) { + header = headers[prop]; + + // skip nullish headers. + if (header == null) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } + } + + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; + +FormData.prototype._getContentDisposition = function (value, options) { // eslint-disable-line consistent-return + var filename; + + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || (value && (value.name || value.path))) { + /* + * custom filename take precedence + * formidable and the browser add a name property + * fs- and request- streams have path property + */ + filename = path.basename(options.filename || (value && (value.name || value.path))); + } else if (value && value.readable && hasOwn(value, 'httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } + + if (filename) { + return 'filename="' + escapeHeaderParam(filename) + '"'; + } +}; + +FormData.prototype._getContentType = function (value, options) { + // use custom content-type above all + var contentType = options.contentType; + + // or try `name` from formidable, browser + if (!contentType && value && value.name) { + contentType = mime.lookup(value.name); + } + + // or try `path` from fs-, request- streams + if (!contentType && value && value.path) { + contentType = mime.lookup(value.path); + } + + // or if it's http-reponse + if (!contentType && value && value.readable && hasOwn(value, 'httpVersion')) { + contentType = value.headers['content-type']; + } + + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + + // fallback to the default content type if `value` is not simple value + if (!contentType && value && typeof value === 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } + + return contentType; +}; + +FormData.prototype._multiPartFooter = function () { + return function (next) { + var footer = FormData.LINE_BREAK; + + var lastPart = this._streams.length === 0; + if (lastPart) { + footer += this._lastBoundary(); + } + + next(footer); + }.bind(this); +}; + +FormData.prototype._lastBoundary = function () { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function (userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { // eslint-disable-line no-restricted-syntax + if (hasOwn(userHeaders, header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + + return formHeaders; +}; + +FormData.prototype.setBoundary = function (boundary) { + if (typeof boundary !== 'string') { + throw new TypeError('FormData boundary must be a string'); + } + this._boundary = boundary; +}; + +FormData.prototype.getBoundary = function () { + if (!this._boundary) { + this._generateBoundary(); + } + + return this._boundary; +}; + +FormData.prototype.getBuffer = function () { + var dataBuffer = new Buffer.alloc(0); // eslint-disable-line new-cap + var boundary = this.getBoundary(); + + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { + // Add content to the buffer. + if (Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); + } else { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); + } + + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring(2, boundary.length + 2) !== boundary) { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData.LINE_BREAK)]); + } + } + } + + // Add the footer and return the Buffer object. + return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); +}; + +FormData.prototype._generateBoundary = function () { + // This generates a 50 character boundary similar to those used by Firefox. + + // They are optimized for boyer-moore parsing. + this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex'); +}; + +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually and add it as knownLength option +FormData.prototype.getLengthSync = function () { + var knownLength = this._overheadLength + this._valueLength; + + // Don't get confused, there are 3 "internal" streams for each keyval pair so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + /* + * Some async length retrievers are present + * therefore synchronous length calculation is false. + * Please use getLength(callback) to get proper length + */ + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } + + return knownLength; +}; + +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function () { + var hasKnownLength = true; + + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } + + return hasKnownLength; +}; + +FormData.prototype.getLength = function (cb) { + var knownLength = this._overheadLength + this._valueLength; + + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } + + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function (err, values) { + if (err) { + cb(err); + return; + } + + values.forEach(function (length) { + knownLength += length; + }); + + cb(null, knownLength); + }); +}; + +FormData.prototype.submit = function (params, cb) { + var request; + var options; + var defaults = { method: 'post' }; + + // parse provided url if it's string or treat it as options object + if (typeof params === 'string') { + params = parseUrl(params); // eslint-disable-line no-param-reassign + /* eslint sort-keys: 0 */ + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); + } else { // use custom params + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol === 'https:' ? 443 : 80; + } + } + + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); + + // https if specified, fallback to http in any other case + if (options.protocol === 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } + + // get content length and fire away + this.getLength(function (err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } + + // add content length + if (length) { + request.setHeader('Content-Length', length); + } + + this.pipe(request); + if (cb) { + var onResponse; + + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); + + return cb.call(this, error, responce); + }; + + onResponse = callback.bind(this, null); + + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); + + return request; +}; + +FormData.prototype._error = function (err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; + +FormData.prototype.toString = function () { + return '[object FormData]'; +}; +setToStringTag(FormData.prototype, 'FormData'); + +// Public API +module.exports = FormData; diff --git a/node_modules/form-data/lib/populate.js b/node_modules/form-data/lib/populate.js new file mode 100644 index 0000000000000000000000000000000000000000..55ac3bb2c455140fa404b1d399a0fd9e518bc722 --- /dev/null +++ b/node_modules/form-data/lib/populate.js @@ -0,0 +1,10 @@ +'use strict'; + +// populates missing values +module.exports = function (dst, src) { + Object.keys(src).forEach(function (prop) { + dst[prop] = dst[prop] || src[prop]; // eslint-disable-line no-param-reassign + }); + + return dst; +}; diff --git a/node_modules/form-data/package.json b/node_modules/form-data/package.json new file mode 100644 index 0000000000000000000000000000000000000000..599287a0010a2b4f2ba40ccac1fb5114c1a848af --- /dev/null +++ b/node_modules/form-data/package.json @@ -0,0 +1,82 @@ +{ + "author": "Felix Geisendörfer (http://debuggable.com/)", + "name": "form-data", + "description": "A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.", + "version": "4.0.6", + "repository": { + "type": "git", + "url": "git://github.com/form-data/form-data.git" + }, + "main": "./lib/form_data", + "browser": "./lib/browser", + "typings": "./index.d.ts", + "scripts": { + "pretest": "npm run lint", + "pretests-only": "rimraf coverage test/tmp", + "tests-only": "istanbul cover test/run.js", + "posttests-only": "istanbul report lcov text", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "lint": "eslint --ext=js,mjs .", + "report": "istanbul report lcov text", + "ci-lint": "is-node-modern 8 && npm run lint || is-node-not-modern 8", + "ci-test": "npm run tests-only && npm run browser && npm run report", + "predebug": "rimraf coverage test/tmp", + "debug": "verbose=1 ./test/run.js", + "browser": "browserify -t browserify-istanbul test/run-browser.js | obake --coverage", + "check": "istanbul check-coverage coverage/coverage*.json", + "files": "pkgfiles --sort=name", + "get-version": "node -e \"console.log(require('./package.json').version)\"", + "update-readme": "sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md", + "postupdate-readme": "mv README.md.bak READ.ME.md.bak", + "restore-readme": "mv READ.ME.md.bak README.md", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepack": "npm run update-readme", + "postpack": "npm run restore-readme", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "engines": { + "node": ">= 6" + }, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "devDependencies": { + "@ljharb/eslint-config": "^22.2.3", + "auto-changelog": "^2.6.0", + "browserify": "^13.3.0", + "browserify-istanbul": "^2.0.0", + "coveralls": "^3.1.1", + "cross-spawn": "^6.0.6", + "eslint": "^8.57.1", + "fake": "^0.2.2", + "far": "^0.0.7", + "formidable": "^1.2.6", + "in-publish": "^2.0.1", + "is-node-modern": "^1.0.0", + "istanbul": "^0.4.5", + "js-randomness-predictor": "^3.6.0", + "obake": "^0.1.2", + "pkgfiles": "^2.3.2", + "pre-commit": "^1.2.2", + "puppeteer": "^1.20.0", + "request": "~2.87.0", + "rimraf": "^2.7.1", + "semver": "^6.3.1", + "tape": "^5.10.1" + }, + "license": "MIT", + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/formidable/LICENSE b/node_modules/formidable/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..5e7ad117520490f1fff2ab5768634fecfa2e174f --- /dev/null +++ b/node_modules/formidable/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011-present Felix Geisendörfer, and contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/formidable/README.md b/node_modules/formidable/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a3990fd53d3ccfebd8cd6ad2dd4869f4d848593d --- /dev/null +++ b/node_modules/formidable/README.md @@ -0,0 +1,891 @@ +

+ npm formidable package logo +

+ +# formidable [![npm version][npmv-img]][npmv-url] [![MIT license][license-img]][license-url] [![Libera Manifesto][libera-manifesto-img]][libera-manifesto-url] [![Twitter][twitter-img]][twitter-url] + +> A Node.js module for parsing form data, especially file uploads. + +[![Code style][codestyle-img]][codestyle-url] +[![linux build status][linux-build-img]][build-url] +[![macos build status][macos-build-img]][build-url] + + +If you have any _how-to_ kind of questions, please read the [Contributing +Guide][contributing-url] and [Code of Conduct][code_of_conduct-url] +documents.
For bugs reports and feature requests, [please create an +issue][open-issue-url] or ping [@wgw_eth / @wgw_lol][twitter-url] +at Twitter. + +[![Conventional Commits][ccommits-img]][ccommits-url] +[![Minimum Required Nodejs][nodejs-img]][npmv-url] +[![Buy me a Kofi][kofi-img]][kofi-url] +[![Make A Pull Request][prs-welcome-img]][prs-welcome-url] + + + +This project is [semantically versioned](https://semver.org) and if you want support in migrating between versions you can schedule us for training or support us through donations, so we can prioritize. + +> [!CAUTION] +> As of April 2025, old versions like v1 and v2 are still the most used, while they are deperecated for years -- they are also vulnerable to attacks if you are not implementing it properly. **Please upgrade!** We are here to help, and AI Editors & Agents could help a lot in such codemod-like migrations. + +> [!TIP] +> If you are starting a fresh project, you can check out the `formidable-mini` which is a super minimal version of Formidable (not quite configurable yet, but when it does it could become the basis for `formidable@v4`), using web standards like FormData API and File API, and you can use it to stream uploads directly to S3 or other such services. + + + +[![][npm-weekly-img]][npmv-url] [![][npm-monthly-img]][npmv-url] +[![][npm-yearly-img]][npmv-url] [![][npm-alltime-img]][npmv-url] + +## Project Status: Maintained + +> [!NOTE] +> Check [VERSION NOTES](https://github.com/node-formidable/formidable/blob/master/VERSION_NOTES.md) for more information on v1, v2, and v3 plans, NPM dist-tags and branches._ + +This module was initially developed by +[**@felixge**](https://github.com/felixge) for +[Transloadit](http://transloadit.com/), a service focused on uploading and +encoding images and videos. It has been battle-tested against hundreds of GBs of +file uploads from a large variety of clients and is considered production-ready +and is used in production for years. + +Currently, we are few maintainers trying to deal with it. :) More contributors +are always welcome! :heart: Jump on +[issue #412](https://github.com/felixge/node-formidable/issues/412) which is +closed, but if you are interested we can discuss it and add you after strict +rules, like enabling Two-Factor Auth in your npm and GitHub accounts. + +## Highlights + +- [Fast (~900-2500 mb/sec)](#benchmarks) & streaming multipart parser +- Automatically writing file uploads to disk (optional, see + [`options.fileWriteStreamHandler`](#options)) +- [Plugins API](#useplugin-plugin) - allowing custom parsers and plugins +- Low memory footprint +- Graceful error handling +- Very high test coverage + +## Install + +This package is a dual ESM/commonjs package. + +> [!NOTE] +> This project requires `Node.js >= 20`. Install it using [yarn](https://yarnpkg.com) or [npm](https://npmjs.com).
_We highly recommend to use Yarn when you think to contribute to this project._ + +This is a low-level package, and if you're using a high-level framework it _may_ +already be included. Check the examples below and the [examples/](https://github.com/node-formidable/formidable/tree/master/examples) folder. + +``` +# v2 +npm install formidable@v2 + +# v3 +npm install formidable +npm install formidable@v3 +``` + +_**Note:** Future not ready releases will be published on `*-next` dist-tags for the corresponding version._ + + +## Examples + +For more examples look at the `examples/` directory. + +### with Node.js http module + +Parse an incoming file upload, with the +[Node.js's built-in `http` module](https://nodejs.org/api/http.html). + +```js +import http from 'node:http'; +import formidable, {errors as formidableErrors} from 'formidable'; + +const server = http.createServer(async (req, res) => { + if (req.url === '/api/upload' && req.method.toLowerCase() === 'post') { + // parse a file upload + const form = formidable({}); + let fields; + let files; + try { + [fields, files] = await form.parse(req); + } catch (err) { + // example to check for a very specific error + if (err.code === formidableErrors.maxFieldsExceeded) { + + } + console.error(err); + res.writeHead(err.httpCode || 400, { 'Content-Type': 'text/plain' }); + res.end(String(err)); + return; + } + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ fields, files }, null, 2)); + return; + } + + // show a file upload form + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` +

With Node.js "http" module

+
+
Text field title:
+
File:
+ +
+ `); +}); + +server.listen(8080, () => { + console.log('Server listening on http://localhost:8080/ ...'); +}); +``` + +### with Express.js + +There are multiple variants to do this, but Formidable just need Node.js Request +stream, so something like the following example should work just fine, without +any third-party [Express.js](https://ghub.now.sh/express) middleware. + +Or try the +[examples/with-express.js](https://github.com/node-formidable/formidable/blob/master/examples/with-express.js) + +```js +import express from 'express'; +import formidable from 'formidable'; + +const app = express(); + +app.get('/', (req, res) => { + res.send(` +

With "express" npm package

+
+
Text field title:
+
File:
+ +
+ `); +}); + +app.post('/api/upload', (req, res, next) => { + const form = formidable({}); + + form.parse(req, (err, fields, files) => { + if (err) { + next(err); + return; + } + res.json({ fields, files }); + }); +}); + +app.listen(3000, () => { + console.log('Server listening on http://localhost:3000 ...'); +}); +``` + +### with Koa and Formidable + +Of course, with [Koa v1, v2 or future v3](https://ghub.now.sh/koa) the things +are very similar. You can use `formidable` manually as shown below or through +the [koa-better-body](https://ghub.now.sh/koa-better-body) package which is +using `formidable` under the hood and support more features and different +request bodies, check its documentation for more info. + +_Note: this example is assuming Koa v2. Be aware that you should pass `ctx.req` +which is Node.js's Request, and **NOT** the `ctx.request` which is Koa's Request +object - there is a difference._ + +```js +import Koa from 'Koa'; +import formidable from 'formidable'; + +const app = new Koa(); + +app.on('error', (err) => { + console.error('server error', err); +}); + +app.use(async (ctx, next) => { + if (ctx.url === '/api/upload' && ctx.method.toLowerCase() === 'post') { + const form = formidable({}); + + // not very elegant, but that's for now if you don't want to use `koa-better-body` + // or other middlewares. + await new Promise((resolve, reject) => { + form.parse(ctx.req, (err, fields, files) => { + if (err) { + reject(err); + return; + } + + ctx.set('Content-Type', 'application/json'); + ctx.status = 200; + ctx.state = { fields, files }; + ctx.body = JSON.stringify(ctx.state, null, 2); + resolve(); + }); + }); + await next(); + return; + } + + // show a file upload form + ctx.set('Content-Type', 'text/html'); + ctx.status = 200; + ctx.body = ` +

With "koa" npm package

+
+
Text field title:
+
File:
+ +
+ `; +}); + +app.use((ctx) => { + console.log('The next middleware is called'); + console.log('Results:', ctx.state); +}); + +app.listen(3000, () => { + console.log('Server listening on http://localhost:3000 ...'); +}); +``` + +## Benchmarks + +The benchmark is quite old, from the old codebase. But maybe quite true though. +Previously the numbers was around ~500 mb/sec. Currently with moving to the new +Node.js Streams API it's faster. You can clearly see the differences between the +Node versions. + +_Note: a lot better benchmarking could and should be done in future._ + +Benchmarked on 8GB RAM, Xeon X3440 (2.53 GHz, 4 cores, 8 threads) + +``` +~/github/node-formidable master +❯ nve --parallel 8 10 12 13 node benchmark/bench-multipart-parser.js + + ⬢ Node 8 + +1261.08 mb/sec + + ⬢ Node 10 + +1113.04 mb/sec + + ⬢ Node 12 + +2107.00 mb/sec + + ⬢ Node 13 + +2566.42 mb/sec +``` + +![benchmark January 29th, 2020](./benchmark/2020-01-29_xeon-x3440.png) + +## API + +### Formidable / IncomingForm + +All shown are equivalent. + +_Please pass [`options`](#options) to the function/constructor, not by assigning +them to the instance `form`_ + +```js +import formidable from 'formidable'; +const form = formidable(options); +``` + +### Options + +See it's defaults in [src/Formidable.js DEFAULT_OPTIONS](./src/Formidable.js) +(the `DEFAULT_OPTIONS` constant). + +- `options.encoding` **{string}** - default `'utf-8'`; sets encoding for + incoming form fields, +- `options.uploadDir` **{string}** - default `os.tmpdir()`; the directory for + placing file uploads in. You can move them later by using `fs.rename()`. +- `options.keepExtensions` **{boolean}** - default `false`; to include the + extensions of the original files or not +- `options.allowEmptyFiles` **{boolean}** - default `false`; allow upload empty + files +- `options.minFileSize` **{number}** - default `1` (1byte); the minium size of + uploaded file. +- `options.maxFiles` **{number}** - default `Infinity`; + limit the amount of uploaded files, set Infinity for unlimited +- `options.maxFileSize` **{number}** - default `200 * 1024 * 1024` (200mb); + limit the size of each uploaded file. +- `options.maxTotalFileSize` **{number}** - default `options.maxFileSize`; + limit the size of the batch of uploaded files. +- `options.maxFields` **{number}** - default `1000`; limit the number of fields, set Infinity for unlimited +- `options.maxFieldsSize` **{number}** - default `20 * 1024 * 1024` (20mb); + limit the amount of memory all fields together (except files) can allocate in + bytes. +- `options.hashAlgorithm` **{string | false}** - default `false`; include checksums calculated + for incoming files, set this to some hash algorithm, see + [crypto.createHash](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options) + for available algorithms +- `options.fileWriteStreamHandler` **{function}** - default `null`, which by + default writes to host machine file system every file parsed; The function + should return an instance of a + [Writable stream](https://nodejs.org/api/stream.html#stream_class_stream_writable) + that will receive the uploaded file data. With this option, you can have any + custom behavior regarding where the uploaded file data will be streamed for. + If you are looking to write the file uploaded in other types of cloud storages + (AWS S3, Azure blob storage, Google cloud storage) or private file storage, + this is the option you're looking for. When this option is defined the default + behavior of writing the file in the host machine file system is lost. +- `options.filename` **{function}** - default `undefined` Use it to control + newFilename. Must return a string. Will be joined with options.uploadDir. + +- `options.filter` **{function}** - default function that always returns true. + Use it to filter files before they are uploaded. Must return a boolean. Will not make the form.parse error + +- `options.createDirsFromUploads` **{boolean}** - default false. If true, makes direct folder uploads possible. Use `` to create a form to upload folders. Has to be used with the options `options.uploadDir` and `options.filename` where `options.filename` has to return a string with the character `/` for folders to be created. The base will be `options.uploadDir`. + + +#### `options.filename` **{function}** function (name, ext, part, form) -> string + +where part can be decomposed as + +```js +const { originalFilename, mimetype} = part; +``` + +_**Note:** If this size of combined fields, or size of some file is exceeded, an +`'error'` event is fired._ + +```js +// The amount of bytes received for this form so far. +form.bytesReceived; +``` + +```js +// The expected number of bytes in this form. +form.bytesExpected; +``` + +#### `options.filter` **{function}** function ({name, originalFilename, mimetype}) -> boolean + +Behaves like Array.filter: Returning false will simply ignore the file and go to the next. + +```js +const options = { + filter: function ({name, originalFilename, mimetype}) { + // keep only images + return mimetype && mimetype.includes("image"); + } +}; +``` + +**Note:** use an outside variable to cancel all uploads upon the first error + +**Note:** use form.emit('error') to make form.parse error + +```js +let cancelUploads = false;// create variable at the same scope as form +const options = { + filter: function ({name, originalFilename, mimetype}) { + // keep only images + const valid = mimetype && mimetype.includes("image"); + if (!valid) { + form.emit('error', new formidableErrors.default('invalid type', 0, 400)); // optional make form.parse error + cancelUploads = true; //variable to make filter return false after the first problem + } + return valid && !cancelUploads; + } +}; +``` + + +### .parse(request, ?callback) + +Parses an incoming Node.js `request` containing form data. If `callback` is not provided a promise is returned. + +```js +const form = formidable({ uploadDir: __dirname }); + +form.parse(req, (err, fields, files) => { + console.log('fields:', fields); + console.log('files:', files); +}); + +// with Promise +const [fields, files] = await form.parse(req); +``` + +You may overwrite this method if you are interested in directly accessing the +multipart stream. Doing so will disable any `'field'` / `'file'` events +processing which would occur otherwise, making you fully responsible for +handling the processing. + +About `uploadDir`, given the following directory structure +``` +project-name +├── src +│ └── server.js +│ +└── uploads + └── image.jpg +``` + +`__dirname` would be the same directory as the source file itself (src) + + +```js + `${__dirname}/../uploads` +``` + +to put files in uploads. + +Omitting `__dirname` would make the path relative to the current working directory. This would be the same if server.js is launched from src but not project-name. + + +`null` will use default which is `os.tmpdir()` + +Note: If the directory does not exist, the uploaded files are __silently discarded__. To make sure it exists: + +```js +import {createNecessaryDirectoriesSync} from "filesac"; + + +const uploadPath = `${__dirname}/../uploads`; +createNecessaryDirectoriesSync(`${uploadPath}/x`); +``` + + +In the example below, we listen on couple of events and direct them to the +`data` listener, so you can do whatever you choose there, based on whether its +before the file been emitted, the header value, the header name, on field, on +file and etc. + +Or the other way could be to just override the `form.onPart` as it's shown a bit +later. + +```js +form.once('error', console.error); + +form.on('fileBegin', (formname, file) => { + form.emit('data', { name: 'fileBegin', formname, value: file }); +}); + +form.on('file', (formname, file) => { + form.emit('data', { name: 'file', formname, value: file }); +}); + +form.on('field', (fieldName, fieldValue) => { + form.emit('data', { name: 'field', key: fieldName, value: fieldValue }); +}); + +form.once('end', () => { + console.log('Done!'); +}); + +// If you want to customize whatever you want... +form.on('data', ({ name, key, value, buffer, start, end, formname, ...more }) => { + if (name === 'partBegin') { + } + if (name === 'partData') { + } + if (name === 'headerField') { + } + if (name === 'headerValue') { + } + if (name === 'headerEnd') { + } + if (name === 'headersEnd') { + } + if (name === 'field') { + console.log('field name:', key); + console.log('field value:', value); + } + if (name === 'file') { + console.log('file:', formname, value); + } + if (name === 'fileBegin') { + console.log('fileBegin:', formname, value); + } +}); +``` + +### .use(plugin: Plugin) + +A method that allows you to extend the Formidable library. By default we include +4 plugins, which essentially are adapters to plug the different built-in parsers. + +**The plugins added by this method are always enabled.** + +_See [src/plugins/](./src/plugins/) for more detailed look on default plugins._ + +The `plugin` param has such signature: + +```typescript +function(formidable: Formidable, options: Options): void; +``` + +The architecture is simple. The `plugin` is a function that is passed with the +Formidable instance (the `form` across the README examples) and the options. + +**Note:** the plugin function's `this` context is also the same instance. + +```js +const form = formidable({ keepExtensions: true }); + +form.use((self, options) => { + // self === this === form + console.log('woohoo, custom plugin'); + // do your stuff; check `src/plugins` for inspiration +}); + +form.parse(req, (error, fields, files) => { + console.log('done!'); +}); +``` + +**Important to note**, is that inside plugin `this.options`, `self.options` and +`options` MAY or MAY NOT be the same. General best practice is to always use the +`this`, so you can later test your plugin independently and more easily. + +If you want to disable some parsing capabilities of Formidable, you can disable +the plugin which corresponds to the parser. For example, if you want to disable +multipart parsing (so the [src/parsers/Multipart.js](./src/parsers/Multipart.js) +which is used in [src/plugins/multipart.js](./src/plugins/multipart.js)), then +you can remove it from the `options.enabledPlugins`, like so + +```js +import formidable, {octetstream, querystring, json} from "formidable"; +const form = formidable({ + hashAlgorithm: 'sha1', + enabledPlugins: [octetstream, querystring, json], +}); +``` + +**Be aware** that the order _MAY_ be important too. The names corresponds 1:1 to +files in [src/plugins/](./src/plugins) folder. + +Pull requests for new built-in plugins MAY be accepted - for example, more +advanced querystring parser. Add your plugin as a new file in `src/plugins/` +folder (lowercased) and follow how the other plugins are made. + +### form.onPart + +If you want to use Formidable to only handle certain parts for you, you can do +something similar. Or see +[#387](https://github.com/node-formidable/node-formidable/issues/387) for +inspiration, you can for example validate the mime-type. + +```js +const form = formidable(); + +form.onPart = (part) => { + part.on('data', (buffer) => { + // do whatever you want here + }); +}; +``` + +For example, force Formidable to be used only on non-file "parts" (i.e., html +fields) + +```js +const form = formidable(); + +form.onPart = function (part) { + // let formidable handle only non-file parts + if (part.originalFilename === '' || !part.mimetype) { + // used internally, please do not override! + form._handlePart(part); + } +}; +``` + +### File + +```ts +export interface File { + // The size of the uploaded file in bytes. + // If the file is still being uploaded (see `'fileBegin'` event), + // this property says how many bytes of the file have been written to disk yet. + file.size: number; + + // The path this file is being written to. You can modify this in the `'fileBegin'` event in + // case you are unhappy with the way formidable generates a temporary path for your files. + file.filepath: string; + + // The name this file had according to the uploading client. + file.originalFilename: string | null; + + // calculated based on options provided + file.newFilename: string | null; + + // The mime type of this file, according to the uploading client. + file.mimetype: string | null; + + // A Date object (or `null`) containing the time this file was last written to. + // Mostly here for compatibility with the [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/). + file.mtime: Date | null; + + file.hashAlgorithm: false | |'sha1' | 'md5' | 'sha256' + // If `options.hashAlgorithm` calculation was set, you can read the hex digest out of this var (at the end it will be a string) + file.hash: string | object | null; +} +``` + +#### file.toJSON() + +This method returns a JSON-representation of the file, allowing you to +`JSON.stringify()` the file which is useful for logging and responding to +requests. + +### Events + +#### `'progress'` + +Emitted after each incoming chunk of data that has been parsed. Can be used to +roll your own progress bar. **Warning** Use this only for server side progress bar. On the client side better use `XMLHttpRequest` with `xhr.upload.onprogress =` + +```js +form.on('progress', (bytesReceived, bytesExpected) => {}); +``` + +#### `'field'` + +Emitted whenever a field / value pair has been received. + +```js +form.on('field', (name, value) => {}); +``` + +#### `'fileBegin'` + +Emitted whenever a new file is detected in the upload stream. Use this event if +you want to stream the file to somewhere else while buffering the upload on the +file system. + +```js +form.on('fileBegin', (formName, file) => { + // accessible here + // formName the name in the form () or http filename for octetstream + // file.originalFilename http filename or null if there was a parsing error + // file.newFilename generated hexoid or what options.filename returned + // file.filepath default pathname as per options.uploadDir and options.filename + // file.filepath = CUSTOM_PATH // to change the final path +}); +``` + +#### `'file'` + +Emitted whenever a field / file pair has been received. `file` is an instance of +`File`. + +```js +form.on('file', (formname, file) => { + // same as fileBegin, except + // it is too late to change file.filepath + // file.hash is available if options.hash was used +}); +``` + +#### `'error'` + +Emitted when there is an error processing the incoming form. A request that +experiences an error is automatically paused, you will have to manually call +`request.resume()` if you want the request to continue firing `'data'` events. + +May have `error.httpCode` and `error.code` attached. + +```js +form.on('error', (err) => {}); +``` + +#### `'aborted'` + +Emitted when the request was aborted by the user. Right now this can be due to a +'timeout' or 'close' event on the socket. After this event is emitted, an +`error` event will follow. In the future there will be a separate 'timeout' +event (needs a change in the node core). + +```js +form.on('aborted', () => {}); +``` + +#### `'end'` + +Emitted when the entire request has been received, and all contained files have +finished flushing to disk. This is a great place for you to send your response. + +```js +form.on('end', () => {}); +``` + + +### Helpers + +#### firstValues + +Gets first values of fields, like pre 3.0.0 without multiples pass in a list of optional exceptions where arrays of strings is still wanted (` +
File:
+ + + `); +}); + +server.listen(8080, () => { + console.log('Server listening on http://localhost:8080/ ...'); +}); +``` + +### com Express.js + +Existem várias variantes para fazer isso, mas o Formidable só precisa do Node.js Request +stream, então algo como o exemplo a seguir deve funcionar bem, sem nenhum middleware [Express.js](https://ghub.now.sh/express) de terceiros. + +Ou tente o +[examples/with-express.js](https://github.com/node-formidable/formidable/blob/master/examples/with-express.js) + +```js +import express from 'express'; +import formidable from 'formidable'; + +const app = express(); + +app.get('/', (req, res) => { + res.send(` +

With "express" npm package

+
+
Text field title:
+
File:
+ +
+ `); +}); + +app.post('/api/upload', (req, res, next) => { + const form = formidable({}); + + form.parse(req, (err, fields, files) => { + if (err) { + next(err); + return; + } + res.json({ fields, files }); + }); +}); + +app.listen(3000, () => { + console.log('Server listening on http://localhost:3000 ...'); +}); +``` + +### com Koa e Formidable + +Claro, com [Koa v1, v2 ou future v3](https://ghub.now.sh/koa) as coisas +sao muito parecidas. Você pode usar `formidable` manualmente como mostrado abaixo ou através +do pacote [koa-better-body](https://ghub.now.sh/koa-better-body) que é +usando `formidable` sob o capô e suporte a mais recursos e diferentes +corpos de solicitação, verifique sua documentação para mais informações. + +_Nota: este exemplo está assumindo Koa v2. Esteja ciente de que você deve passar `ctx.req` +que é a solicitação do Node.js e **NÃO** o `ctx.request` que é a solicitação do Koa +objeto - há uma diferença._ + +```js +import Koa from 'Koa'; +import formidable from 'formidable'; + +const app = new Koa(); + +app.on('error', (err) => { + console.error('server error', err); +}); + +app.use(async (ctx, next) => { + if (ctx.url === '/api/upload' && ctx.method.toLowerCase() === 'post') { + const form = formidable({}); + + // não muito elegante, mas é por enquanto se você não quiser usar `koa-better-body` + // ou outros middlewares. + await new Promise((resolve, reject) => { + form.parse(ctx.req, (err, fields, files) => { + if (err) { + reject(err); + return; + } + + ctx.set('Content-Type', 'application/json'); + ctx.status = 200; + ctx.state = { fields, files }; + ctx.body = JSON.stringify(ctx.state, null, 2); + resolve(); + }); + }); + await next(); + return; + } + + // mostrar um formulário de upload de arquivo + ctx.set('Content-Type', 'text/html'); + ctx.status = 200; + ctx.body = ` +

With "koa" npm package

+
+
Text field title:
+
File:
+ +
+ `; +}); + +app.use((ctx) => { + console.log('The next middleware is called'); + console.log('Results:', ctx.state); +}); + +app.listen(3000, () => { + console.log('Server listening on http://localhost:3000 ...'); +}); +``` + +## Benchmarks + +O benchmark é bastante antigo, da antiga base de código. Mas talvez seja bem verdade. +Anteriormente, os números giravam em torno de ~ 500 mb/s. Atualmente com a mudança para o novo +Node.js Streams API, é mais rápido. Você pode ver claramente as diferenças entre as +versões do Node. + +_Observação: um benchmarking muito melhor pode e deve ser feito no futuro._ + +Benchmark realizado em 8 GB de RAM, Xeon X3440 (2,53 GHz, 4 núcleos, 8 threads) + +``` +~/github/node-formidable master +❯ nve --parallel 8 10 12 13 node benchmark/bench-multipart-parser.js + + ⬢ Node 8 + +1261.08 mb/sec + + ⬢ Node 10 + +1113.04 mb/sec + + ⬢ Node 12 + +2107.00 mb/sec + + ⬢ Node 13 + +2566.42 mb/sec +``` + +![benchmark 29 de janeiro de 2020](./benchmark/2020-01-29_xeon-x3440.png) + +## API + +### Formidable / IncomingForm + +Todos os mostrados são equivalentes. + +_Por favor, passe [`options`](#options) para a função/construtor, não atribuindo +eles para a instância `form`_ + +```js +import formidable from 'formidable'; +const form = formidable(options); +``` + +### Opções + +Veja seus padrões em [src/Formidable.js DEFAULT_OPTIONS](./src/Formidable.js) +(a constante `DEFAULT_OPTIONS`). + +- `options.encoding` **{string}** - padrão `'utf-8'`; define a codificação para campos de formulário de entrada, +- `options.uploadDir` **{string}** - padrão `os.tmpdir()`; o diretório para colocar os uploads de arquivos. Você pode movê-los mais tarde usando `fs.rename()`. +- `options.keepExtensions` **{boolean}** - padrão `false`; incluir as extensões dos arquivos originais ou não +- `options.allowEmptyFiles` **{boolean}** - padrão `false`; permitir upload de arquivos vazios +- `options.minFileSize` **{number}** - padrão `1` (1byte); o tamanho mínimo do arquivo carregado. +- `options.maxFiles` **{number}** - padrão `Infinity`; + limitar a quantidade de arquivos carregados, defina Infinity para ilimitado +- `options.maxFileSize` **{number}** - padrão `200 * 1024 * 1024` (200mb); + limitar o tamanho de cada arquivo carregado. +- `options.maxTotalFileSize` **{number}** - padrão `options.maxFileSize`; + limitar o tamanho do lote de arquivos carregados. +- `options.maxFields` **{number}** - padrão `1000`; limite o número de campos, defina Infinity para ilimitado +- `options.maxFieldsSize` **{number}** - padrão `20 * 1024 * 1024` (20mb); + limitar a quantidade de memória que todos os campos juntos (exceto arquivos) podem alocar em + bytes. +- `options.hashAlgorithm` **{string | false}** - padrão `false`; incluir checksums calculados + para arquivos recebidos, defina isso para algum algoritmo de hash, consulte + [crypto.createHash](https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options) + para algoritmos disponíveis +- `options.fileWriteStreamHandler` **{function}** - padrão `null`, que por padrão grava no sistema de arquivos da máquina host cada arquivo analisado; A função + deve retornar uma instância de um + [fluxo gravável](https://nodejs.org/api/stream.html#stream_class_stream_writable) + que receberá os dados do arquivo carregado. Com esta opção, você pode ter qualquer + comportamento personalizado em relação a onde os dados do arquivo carregado serão transmitidos. + Se você deseja gravar o arquivo carregado em outros tipos de armazenamento em nuvem + (AWS S3, armazenamento de blob do Azure, armazenamento em nuvem do Google) ou armazenamento de arquivo privado, + esta é a opção que você está procurando. Quando esta opção é definida, o comportamento padrão de gravar o arquivo no sistema de arquivos da máquina host é perdido. +- `options.filename` **{function}** - padrão `undefined` Use-o para controlar newFilename. Deve retornar uma string. Será associado a options.uploadDir. + +- `options.filter` **{function}** - função padrão que sempre retorna verdadeiro. + Use-o para filtrar arquivos antes de serem carregados. Deve retornar um booleano. + + +#### `options.filename` **{function}** function (name, ext, part, form) -> string + +onde a parte pode ser decomposta como + +```js +const { originalFilename, mimetype} = part; +``` + +_**Observação:** Se este tamanho de campos combinados, ou tamanho de algum arquivo for excedido, um +O evento `'error'` é disparado._ + +```js +// A quantidade de bytes recebidos para este formulário até agora. +form.bytesReceived; +``` + +```js +// O número esperado de bytes neste formulário. +form.bytesExpected; +``` + +#### `options.filter` **{function}** function ({name, originalFilename, mimetype}) -> boolean + +**Observação:** use uma variável externa para cancelar todos os uploads no primeiro erro + +```js +const options = { + filter: function ({name, originalFilename, mimetype}) { + // manter apenas imagens + return mimetype && mimetype.includes("image"); + } +}; +``` + + +### .parse(request, callback) + +Analisa uma `request` do Node.js recebida contendo dados de formulário. Se `callback` for +fornecido, todos os campos e arquivos são coletados e passados para o retorno de chamada. + +```js +const form = formidable({ uploadDir: __dirname }); + +form.parse(req, (err, fields, files) => { + console.log('fields:', fields); + console.log('files:', files); +}); +``` + +Você pode substituir esse método se estiver interessado em acessar diretamente o +fluxo de várias partes. Fazer isso desativará qualquer processamento de eventos `'field'` / `'file'` +que ocorreria de outra forma, tornando você totalmente responsável por lidar com o processamento. + +Sobre `uploadDir`, dada a seguinte estrutura de diretório +``` +project-name +├── src +│ └── server.js +│ +└── uploads + └── image.jpg +``` + +`__dirname` seria o mesmo diretório que o próprio arquivo de origem (src) + + +```js + `${__dirname}/../uploads` +``` + +para colocar arquivos em uploads. + +Omitir `__dirname` tornaria o caminho relativo ao diretório de trabalho atual. Isso seria o mesmo se server.js fosse iniciado a partir de src, mas não de project-name. + + +`null` usará o padrão que é `os.tmpdir()` + +Nota: Se o diretório não existir, os arquivos carregados são __silenciosamente descartados__. Para ter certeza de que existe: + +```js +import {createNecessaryDirectoriesSync} from "filesac"; + + +const uploadPath = `${__dirname}/../uploads`; +createNecessaryDirectoriesSync(`${uploadPath}/x`); +``` + + +No exemplo abaixo, escutamos alguns eventos e os direcionamos para o ouvinte `data`, para +que você possa fazer o que quiser lá, com base em se é antes do arquivo ser emitido, o valor do +cabeçalho, o nome do cabeçalho, no campo , em arquivo e etc. + +Ou a outra maneira poderia ser apenas substituir o `form.onPart` como é mostrado um pouco +mais tarde. + +```js +form.once('error', console.error); + +form.on('fileBegin', (formname, file) => { + form.emit('data', { name: 'fileBegin', formname, value: file }); +}); + +form.on('file', (formname, file) => { + form.emit('data', { name: 'file', formname, value: file }); +}); + +form.on('field', (fieldName, fieldValue) => { + form.emit('data', { name: 'field', key: fieldName, value: fieldValue }); +}); + +form.once('end', () => { + console.log('Done!'); +}); + +// Se você quiser personalizar o que quiser... +form.on('data', ({ name, key, value, buffer, start, end, formname, ...more }) => { + if (name === 'partBegin') { + } + if (name === 'partData') { + } + if (name === 'headerField') { + } + if (name === 'headerValue') { + } + if (name === 'headerEnd') { + } + if (name === 'headersEnd') { + } + if (name === 'field') { + console.log('field name:', key); + console.log('field value:', value); + } + if (name === 'file') { + console.log('file:', formname, value); + } + if (name === 'fileBegin') { + console.log('fileBegin:', formname, value); + } +}); +``` + +### .use(plugin: Plugin) + +Um método que permite estender a biblioteca Formidable. Por padrão, incluímos +4 plug-ins, que são essencialmente adaptadores para conectar os diferentes analisadores integrados. + +**Os plugins adicionados por este método estão sempre ativados.** + +_Consulte [src/plugins/](./src/plugins/) para uma visão mais detalhada dos plug-ins padrão._ + +O parâmetro `plugin` tem essa assinatura: + +```typescript +function(formidable: Formidable, options: Options): void; +``` + +A arquitetura é simples. O `plugin` é uma função que é passada com a instância Formidable (o `form` nos exemplos README) e as opções. + +**Observação:** o contexto `this` da função do plug-in também é a mesma instância. + +```js +const form = formidable({ keepExtensions: true }); + +form.use((self, options) => { + // self === this === form + console.log('woohoo, custom plugin'); + // faça suas coisas; verifique `src/plugins` para inspiração +}); + +form.parse(req, (error, fields, files) => { + console.log('done!'); +}); +``` +**Importante observar**, é que dentro do plugin `this.options`, `self.options` e +`options` PODEM ou NÃO ser iguais. A melhor prática geral é sempre usar o +`this`, para que você possa testar seu plugin mais tarde de forma independente e mais fácil. + +Se você quiser desabilitar alguns recursos de análise do Formidable, você pode desabilitar +o plugin que corresponde ao analisador. Por exemplo, se você deseja desabilitar a análise de +várias partes (para que o [src/parsers/Multipart.js](./src/parsers/Multipart.js) +que é usado em [src/plugins/multipart.js](./src/plugins/multipart.js)), então +você pode removê-lo do `options.enabledPlugins`, assim + +```js +import formidable, {octetstream, querystring, json} from "formidable"; +const form = formidable({ + hashAlgorithm: 'sha1', + enabledPlugins: [octetstream, querystring, json], +}); +``` + +**Esteja ciente** de que a ordem _PODE_ ser importante também. Os nomes correspondem 1:1 a +arquivos na pasta [src/plugins/](./src/plugins). + +Solicitações pull para novos plug-ins integrados PODEM ser aceitas - por exemplo, analisador de +querystring mais avançado. Adicione seu plugin como um novo arquivo na pasta `src/plugins/` (em letras minúsculas) e +siga como os outros plugins são feitos. + +### form.onPart + +Se você quiser usar Formidable para manipular apenas algumas partes para você, você pode fazer +alguma coisa similar. ou ver +[#387](https://github.com/node-formidable/node-formidable/issues/387) para +inspiração, você pode, por exemplo, validar o tipo mime. + +```js +const form = formidable(); + +form.onPart = (part) => { + part.on('data', (buffer) => { + // faça o que quiser aqui + }); +}; +``` + +Por exemplo, force Formidable a ser usado apenas em "partes" que não sejam de arquivo (ou seja, html +Campos) + +```js +const form = formidable(); + +form.onPart = function (part) { + // deixe formidável lidar apenas com partes não arquivadas + if (part.originalFilename === '' || !part.mimetype) { + // usado internamente, por favor, não substitua! + form._handlePart(part); + } +}; +``` + +### Arquivo + +```ts +export interface File { + // O tamanho do arquivo enviado em bytes. + // Se o arquivo ainda estiver sendo carregado (veja o evento `'fileBegin'`), + // esta propriedade diz quantos bytes do arquivo já foram gravados no disco. + file.size: number; + + // O caminho em que este arquivo está sendo gravado. Você pode modificar isso no evento `'fileBegin'` + // caso você esteja insatisfeito com a forma como o formidable gera um caminho temporário para seus arquivos. + file.filepath: string; + + // O nome que este arquivo tinha de acordo com o cliente de upload. + file.originalFilename: string | null; + + // calculado com base nas opções fornecidas. + file.newFilename: string | null; + + // O tipo mime deste arquivo, de acordo com o cliente de upload. + file.mimetype: string | null; + + // Um objeto Date (ou `null`) contendo a hora em que este arquivo foi gravado pela última vez. + // Principalmente aqui para compatibilidade com o [W3C File API Draft](http://dev.w3.org/2006/webapi/FileAPI/). + file.mtime: Date | null; + + file.hashAlgorithm: false | |'sha1' | 'md5' | 'sha256' + // Se o cálculo `options.hashAlgorithm` foi definido, você pode ler o resumo hexadecimal desta var (no final, será uma string) + file.hash: string | object | null; +} +``` + +#### file.toJSON() + +Este método retorna uma representação JSON do arquivo, permitindo que você `JSON.stringify()` +o arquivo que é útil para registrar e responder a solicitações. + +### Eventos + +#### `'progress'` +Emitido após cada bloco de entrada de dados que foi analisado. Pode ser usado para rolar sua própria barra de progresso. **Aviso** Use isso +apenas para a barra de progresso do lado do servidor. No lado do cliente, é melhor usar `XMLHttpRequest` com `xhr.upload.onprogress =` + +```js +form.on('progress', (bytesReceived, bytesExpected) => {}); +``` + +#### `'field'` + +Emitido sempre que um par campo/valor é recebido. + +```js +form.on('field', (name, value) => {}); +``` + +#### `'fileBegin'` + +Emitido sempre que um novo arquivo é detectado no fluxo de upload. +Use este evento se desejar transmitir o arquivo para outro lugar enquanto armazena o upload no sistema de arquivos. + +```js +form.on('fileBegin', (formName, file) => { + // acessível aqui + // formName o nome no formulário () ou http filename para octetstream + // file.originalFilename http filename ou null se houver um erro de análise + // file.newFilename gerou hexoid ou o que options.filename retornou + // file.filepath nome do caminho padrão de acordo com options.uploadDir e options.filename + // file.filepath = CUSTOM_PATH // para alterar o caminho final +}); +``` + +#### `'file'` + +Emitido sempre que um par campo/arquivo é recebido. `file` é uma instância de +`File`. + +```js +form.on('file', (formname, file) => { + // o mesmo que fileBegin, exceto + // é muito tarde para alterar file.filepath + // file.hash está disponível se options.hash foi usado +}); +``` + +#### `'error'` + +Emitido quando há um erro no processamento do formulário recebido. Uma solicitação que +apresenta um erro é pausada automaticamente, você terá que chamar manualmente +`request.resume()` se você quiser que a requisição continue disparando eventos `'data'`. + +Pode ter `error.httpCode` e `error.code` anexados. + +```js +form.on('error', (err) => {}); +``` + +#### `'aborted'` + +Emitido quando a requisição foi abortada pelo usuário. Agora isso pode ser devido a um +evento 'timeout' ou 'close' no soquete. Após este evento ser emitido, um +O evento `error` seguirá. No futuro, haverá um 'timeout' separado +evento (precisa de uma mudança no núcleo do nó). + +```js +form.on('aborted', () => {}); +``` + +#### `'end'` + +Emitido quando toda a solicitação foi recebida e todos os arquivos contidos foram +liberados para o disco. Este é um ótimo lugar para você enviar sua resposta. + +```js +form.on('end', () => {}); +``` + + +### Helpers + +#### firstValues + +Obtém os primeiros valores dos campos, como pré 3.0.0 sem passar múltiplos em uma +lista de exceções opcionais onde arrays de strings ainda são desejados (`