repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
placemark | github_2023 | placemark | typescript | syntheticPointsForRing | function syntheticPointsForRing({
ring,
syntheticPoints,
index,
offset,
ringType,
}: {
ring: Position[];
syntheticPoints: IFeature<Point>[];
index: number;
offset: number;
ringType: RingType;
}) {
// The last point of a polygon is repeated, don’t create
// a vertex for it because it would be overlapping.
const end = ring.length - (ringType === RingType.Polygon ? 1 : 0);
for (let i = 0; i < end; i++) {
syntheticPoints.push(
new Vertex(
encodeVertex(index, offset),
ring[i],
ringType === RingType.Point
)
);
if (ringType !== RingType.Point && i < ring.length - 1) {
syntheticPoints.push(
new Midpoint(
encodeMidpoint(index, offset),
midpoint(ring[i], ring[i + 1])
)
);
}
offset++;
}
return offset;
} | /**
* @param index - The feature part of the ID that will be generated for each
* Vertex.
* @param offset - In the case where there are multiple rings, this is the
* offset of this ring - the number of vertexes already accounted for in previous
* rings.
* @param notLooped - Polygon rings repeat the last coordinate, but LineStrings
* do not. We want one vertex for that last coordinate, not two.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/pmap/generate_synthetic_points.ts#L67-L102 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | syntheticPointsForPoint | function syntheticPointsForPoint({
geometry,
syntheticPoints,
index,
offset,
}: {
geometry: Point;
syntheticPoints: IFeature<Point>[];
index: number;
offset: number;
}) {
syntheticPoints.push(
new Vertex(encodeVertex(index, offset), geometry.coordinates, true)
);
return offset + 1;
} | /**
* INCREMENT: 1
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/pmap/generate_synthetic_points.ts#L176-L191 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | syntheticPointsForMultiPoint | function syntheticPointsForMultiPoint({
geometry,
syntheticPoints,
index,
offset,
}: {
geometry: MultiPoint;
syntheticPoints: IFeature<Point>[];
index: number;
offset: number;
}) {
return syntheticPointsForRing({
ring: geometry.coordinates,
syntheticPoints,
index,
offset,
ringType: RingType.Point,
});
} | /**
* INCREMENT: # of points
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/pmap/generate_synthetic_points.ts#L196-L214 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | syntheticPointsForMultiLineString | function syntheticPointsForMultiLineString({
geometry,
syntheticPoints,
index,
offset,
}: {
geometry: MultiLineString;
syntheticPoints: IFeature<Point>[];
index: number;
offset: number;
}) {
for (const line of geometry.coordinates) {
offset = syntheticPointsForRing({
ring: line,
syntheticPoints,
index,
offset,
ringType: RingType.LineString,
});
}
return offset;
} | /**
* INCREMENT: # of vertexes
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/pmap/generate_synthetic_points.ts#L219-L240 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | mSetData | function mSetData(
source: mapboxgl.GeoJSONSource,
newData: Feature[],
_label: string,
force?: boolean
) {
if (!shallowArrayEqual(lastValues.get(source), newData) || force) {
source.setData({
type: "FeatureCollection",
features: newData,
} as IFeatureCollection);
lastValues.set(source, newData);
} else {
// console.log(
// "Skipped update",
// _label,
// source,
// newData,
// lastValues.get(source)
// );
}
} | /**
* Memoized set data for a mapboxgl.GeoJSONSource. If
* the same source is called with the same data,
* it won't set.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/pmap/index.ts#L82-L103 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | PMap.onClick | onClick = (e: LayerScopedEvent) => {
this.handlers.current.onClick(e);
} | /**
* Handler proxies --------------------------------------
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/pmap/index.ts | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | PMap.setData | setData({
data,
ephemeralState,
force = false,
}: {
data: Data;
ephemeralState: EphemeralEditingState;
force?: boolean;
}) {
if (!(this.map && (this.map as any).style)) {
this.lastData = data;
return;
}
const featuresSource = this.map.getSource(
FEATURES_SOURCE_NAME
) as mapboxgl.GeoJSONSource;
const ephemeralSource = this.map.getSource(
EPHEMERAL_SOURCE_NAME
) as mapboxgl.GeoJSONSource;
if (!featuresSource || !ephemeralSource) {
// Set the lastFeatureList here
// so that the setStyle method will
// add it again. This happens when the map
// is initially loaded.
this.lastData = data;
return;
}
const groups = splitFeatureGroups({
idMap: this.idMap,
data,
lastSymbolization: this.lastSymbolization,
previewProperty: this.lastPreviewProperty,
});
// console.log(
// "in setData",
// JSON.stringify({
// newSelection,
// outputIds: [...groups.selectionIds],
// })
// );
// TODO: fix flash
mSetData(ephemeralSource, groups.ephemeral, "ephem");
mSetData(featuresSource, groups.features, "features", force);
this.overlay.setProps({
layers: [
new ScatterplotLayer<IFeature<Point>>({
id: DECK_SYNTHETIC_ID,
radiusUnits: "pixels",
lineWidthUnits: "pixels",
pickable: true,
stroked: true,
filled: true,
data: groups.synthetic,
getPosition: (d) => d.geometry.coordinates as [number, number],
getFillColor: (d) => {
return groups.selectionIds.has(d.id as RawId)
? WHITE
: LINE_COLORS_SELECTED_RGB;
},
getLineColor: (d) => {
return groups.selectionIds.has(d.id as RawId)
? LINE_COLORS_SELECTED_RGB
: WHITE;
},
getLineWidth: 1.5,
getRadius: (d) => {
const id = Number(d.id || 0);
const fp = d.properties?.fp;
if (fp) return 10;
return id % 2 === 0 ? 5 : 3.5;
},
}),
ephemeralState.type === "lasso" &&
new PolygonLayer<number[]>({
id: DECK_LASSO_ID,
data: [makeRectangle(ephemeralState)],
visible: ephemeralState.type === "lasso",
pickable: false,
stroked: true,
filled: true,
lineWidthUnits: "pixels",
getPolygon: (d) => d,
getFillColor: LASSO_YELLOW,
getLineColor: LASSO_DARK_YELLOW,
getLineWidth: 1,
}),
],
});
this.lastData = data;
this.updateSelections(groups.selectionIds);
this.lastEphemeralState = ephemeralState;
} | /**
* The central hard method, trying to optimize feature updates
* on the map.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/pmap/index.ts#L270-L373 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | PMap.setStyle | async setStyle({
layerConfigs,
symbolization,
previewProperty,
}: {
layerConfigs: LayerConfigMap;
symbolization: ISymbolization;
previewProperty: PreviewProperty;
}) {
if (
layerConfigs === this.lastLayer &&
symbolization === this.lastSymbolization &&
previewProperty === this.lastPreviewProperty
) {
return;
}
this.lastLayer = layerConfigs;
this.lastSymbolization = symbolization;
this.lastPreviewProperty = previewProperty;
const style = await loadAndAugmentStyle({
layerConfigs,
symbolization,
previewProperty,
});
this.map.setStyle(style);
await new Promise((resolve) => setTimeout(resolve, 100));
if (this.lastData) {
this.setData({
data: this.lastData,
ephemeralState: this.lastEphemeralState,
force: true,
});
this.lastSelection = { type: "none" };
}
} | // a style.load event. | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/app/lib/pmap/index.ts#L382-L418 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | handleRequest | async function handleRequest(event) {
const request = event.request;
if (request.method == "OPTIONS") {
const response = new Response("", { status: 200 });
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Max-Age", "86400");
return response;
}
if (request.method !== "GET") {
return new Response("Invalid method", { status: 405 });
}
const cacheUrl = new URL(request.url);
// Construct the cache key from the cache URL
const cacheKey = new Request(cacheUrl.toString(), request);
const cache = caches.default;
const { pathname, search } = new URL(request.url);
if (!pathname.startsWith("/api/v1")) {
return new Response(`Invalid request`, { status: 404 });
}
let response = await cache.match(request);
if (!response) {
console.log("not cached");
const apiUrl = `https://your.placemark.server.com${pathname}${search}`;
const originRequest = new Request(apiUrl, request);
originRequest.headers.set("Origin", new URL(apiUrl).origin);
response = await fetch(originRequest, {
cf: {
// Always cache this fetch regardless of content type
// for a max of 5 seconds before revalidating the resource
cacheTtl: 20,
cacheEverything: true,
},
});
// Reconstruct the Response object to make its headers mutable.
response = new Response(response.body, response);
// Set cache control headers to cache on browser for 25 minutes
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Max-Age", "86400");
response.headers.set(
"Cache-Control",
"max-age=30, stale-while-revalidate=60",
);
event.waitUntil(cache.put(cacheKey, response.clone()));
} else {
console.log("found in cache");
}
return response;
} | /**
* @param {Request} request
* @returns {Promise<Response>}
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/docs/worker_example.ts#L22-L79 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | uniqueStops | function uniqueStops<T extends { input: JsonValue }>(stops: T[]): T[] {
const inputs = new Set();
const transformedStops = [];
for (const stop of stops) {
if (!inputs.has(stop.input)) {
inputs.add(stop.input);
transformedStops.push(stop);
}
}
return transformedStops;
} | /**
* Make stops unique based on their 'input' value.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/types/index.ts#L332-L343 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | GreatCircle.interpolate | interpolate(f: number): Pos2 {
const A = Math.sin((1 - f) * this.g) / Math.sin(this.g);
const B = Math.sin(f * this.g) / Math.sin(this.g);
const x =
A * Math.cos(this.start.y) * Math.cos(this.start.x) +
B * Math.cos(this.end.y) * Math.cos(this.end.x);
const y =
A * Math.cos(this.start.y) * Math.sin(this.start.x) +
B * Math.cos(this.end.y) * Math.sin(this.end.x);
const z = A * Math.sin(this.start.y) + B * Math.sin(this.end.y);
const lat = R2D * Math.atan2(z, Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)));
const lon = R2D * Math.atan2(y, x);
return [lon, lat];
} | /*
* http://williams.best.vwh.net/avform.htm#Intermediate
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/arc.ts#L108-L121 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | GreatCircle.arc | arc(npoints?: number, options?: { offset?: number }): Geometry | null {
const first_pass: Pos2[] = [];
if (!npoints || npoints <= 2) {
first_pass.push([this.start.lon, this.start.lat]);
first_pass.push([this.end.lon, this.end.lat]);
} else {
const delta = 1.0 / (npoints - 1);
for (let i = 0; i < npoints; ++i) {
const step = delta * i;
const pair = this.interpolate(step);
first_pass.push(pair);
}
}
/* partial port of dateline handling from:
gdal/ogr/ogrgeometryfactory.cpp
TODO - does not handle all wrapping scenarios yet
*/
let bHasBigDiff = false;
let dfMaxSmallDiffLong = 0;
// from http://www.gdal.org/ogr2ogr.html
// -datelineoffset:
// (starting with GDAL 1.10) offset from dateline in degrees (default long. = +/- 10deg, geometries within 170deg to -170deg will be splited)
const dfDateLineOffset = options && options.offset ? options.offset : 10;
const dfLeftBorderX = 180 - dfDateLineOffset;
const dfRightBorderX = -180 + dfDateLineOffset;
const dfDiffSpace = 360 - dfDateLineOffset;
// https://github.com/OSGeo/gdal/blob/7bfb9c452a59aac958bff0c8386b891edf8154ca/gdal/ogr/ogrgeometryfactory.cpp#L2342
for (let j = 1; j < first_pass.length; ++j) {
const dfPrevX = first_pass[j - 1][0];
const dfX = first_pass[j][0];
const dfDiffLong = Math.abs(dfX - dfPrevX);
if (
dfDiffLong > dfDiffSpace &&
((dfX > dfLeftBorderX && dfPrevX < dfRightBorderX) ||
(dfPrevX > dfLeftBorderX && dfX < dfRightBorderX))
) {
bHasBigDiff = true;
} else if (dfDiffLong > dfMaxSmallDiffLong) {
dfMaxSmallDiffLong = dfDiffLong;
}
}
const poMulti = [];
if (bHasBigDiff && dfMaxSmallDiffLong < dfDateLineOffset) {
let poNewLS: Pos2[] = [];
poMulti.push(poNewLS);
for (let k = 0; k < first_pass.length; ++k) {
const dfX0 = first_pass[k][0];
if (k > 0 && Math.abs(dfX0 - first_pass[k - 1][0]) > dfDiffSpace) {
let dfX1 = first_pass[k - 1][0];
let dfY1 = first_pass[k - 1][1];
let dfX2 = first_pass[k][0];
let dfY2 = first_pass[k][1];
if (
dfX1 > -180 &&
dfX1 < dfRightBorderX &&
dfX2 == 180 &&
k + 1 < first_pass.length &&
first_pass[k - 1][0] > -180 &&
first_pass[k - 1][0] < dfRightBorderX
) {
poNewLS.push([-180, first_pass[k][1]]);
k++;
poNewLS.push([first_pass[k][0], first_pass[k][1]]);
continue;
} else if (
dfX1 > dfLeftBorderX &&
dfX1 < 180 &&
dfX2 == -180 &&
k + 1 < first_pass.length &&
first_pass[k - 1][0] > dfLeftBorderX &&
first_pass[k - 1][0] < 180
) {
poNewLS.push([180, first_pass[k][1]]);
k++;
poNewLS.push([first_pass[k][0], first_pass[k][1]]);
continue;
}
if (dfX1 < dfRightBorderX && dfX2 > dfLeftBorderX) {
// swap dfX1, dfX2
const tmpX = dfX1;
dfX1 = dfX2;
dfX2 = tmpX;
// swap dfY1, dfY2
const tmpY = dfY1;
dfY1 = dfY2;
dfY2 = tmpY;
}
if (dfX1 > dfLeftBorderX && dfX2 < dfRightBorderX) {
dfX2 += 360;
}
if (dfX1 <= 180 && dfX2 >= 180 && dfX1 < dfX2) {
const dfRatio = (180 - dfX1) / (dfX2 - dfX1);
const dfY = dfRatio * dfY2 + (1 - dfRatio) * dfY1;
poNewLS.push([
first_pass[k - 1][0] > dfLeftBorderX ? 180 : -180,
dfY,
]);
poNewLS = [];
poNewLS.push([
first_pass[k - 1][0] > dfLeftBorderX ? -180 : 180,
dfY,
]);
poMulti.push(poNewLS);
} else {
poNewLS = [];
poMulti.push(poNewLS);
}
poNewLS.push([dfX0, first_pass[k][1]]);
} else {
poNewLS.push([first_pass[k][0], first_pass[k][1]]);
}
}
} else {
// add normally
const poNewLS0: Pos2[] = [];
poMulti.push(poNewLS0);
for (let l = 0; l < first_pass.length; ++l) {
poNewLS0.push([first_pass[l][0], first_pass[l][1]]);
}
}
const arc = new Arc();
for (let m = 0; m < poMulti.length; ++m) {
const line = new LineString();
arc.geometries.push(line);
const points = poMulti[m];
for (let j0 = 0; j0 < points.length; ++j0) {
line.move_to(points[j0]);
}
}
return arc.json();
} | /*
* Generate points along the great circle
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/arc.ts#L126-L262 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | sqSegBoxDist | function sqSegBoxDist(a: Pos2, b: Pos2, bbox: any) {
if (inside(a, bbox) || inside(b, bbox)) return 0;
const d1 = sqSegSegDist(
a[0],
a[1],
b[0],
b[1],
bbox.minX,
bbox.minY,
bbox.maxX,
bbox.minY
);
if (d1 === 0) return 0;
const d2 = sqSegSegDist(
a[0],
a[1],
b[0],
b[1],
bbox.minX,
bbox.minY,
bbox.minX,
bbox.maxY
);
if (d2 === 0) return 0;
const d3 = sqSegSegDist(
a[0],
a[1],
b[0],
b[1],
bbox.maxX,
bbox.minY,
bbox.maxX,
bbox.maxY
);
if (d3 === 0) return 0;
const d4 = sqSegSegDist(
a[0],
a[1],
b[0],
b[1],
bbox.minX,
bbox.maxY,
bbox.maxX,
bbox.maxY
);
if (d4 === 0) return 0;
return Math.min(d1, d2, d3, d4);
} | // square distance from a segment bounding box to the given one | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L282-L329 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | noIntersections | function noIntersections(a: Pos2, b: Pos2, segTree: RBush<LinkedNode>) {
const minX = Math.min(a[0], b[0]);
const minY = Math.min(a[1], b[1]);
const maxX = Math.max(a[0], b[0]);
const maxY = Math.max(a[1], b[1]);
const edges = segTree.search({
minX: minX,
minY: minY,
maxX: maxX,
maxY: maxY,
});
for (let i = 0; i < edges.length; i++) {
if (intersects(edges[i].p, edges[i].next!.p, a, b)) return false;
}
return true;
} | // check if the edge (a,b) doesn't intersect any other edges | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L341-L357 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | intersects | function intersects(p1: Pos2, q1: Pos2, p2: Pos2, q2: Pos2) {
return (
p1 !== q2 &&
q1 !== p2 &&
cross(p1, q1, p2) > 0 !== cross(p1, q1, q2) > 0 &&
cross(p2, q2, p1) > 0 !== cross(p2, q2, q1) > 0
);
} | // check if the edges (p1,q1) and (p2,q2) intersect | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L364-L371 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | updateBBox | function updateBBox(node: LinkedNode) {
const p1 = node.p;
const p2 = node.next!.p;
node.minX = Math.min(p1[0], p2[0]);
node.minY = Math.min(p1[1], p2[1]);
node.maxX = Math.max(p1[0], p2[0]);
node.maxY = Math.max(p1[1], p2[1]);
return node;
} | // update the bounding box of a node's edge | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L374-L382 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | fastConvexHull | function fastConvexHull(points: Pos2[]) {
let left = points[0];
let top = points[0];
let right = points[0];
let bottom = points[0];
// find the leftmost, rightmost, topmost and bottommost points
for (let i = 0; i < points.length; i++) {
const p = points[i];
if (p[0] < left[0]) left = p;
if (p[0] > right[0]) right = p;
if (p[1] < top[1]) top = p;
if (p[1] > bottom[1]) bottom = p;
}
// filter out points that are inside the resulting quadrilateral
const cull = [left, top, right, bottom];
const filtered = cull.slice();
for (let i = 0; i < points.length; i++) {
if (!pointInPolygon(points[i], cull)) filtered.push(points[i]);
}
// get convex hull around the filtered points
return convexHull(filtered);
} | // speed up convex hull by filtering out points inside quadrilateral formed by 4 extreme points | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L385-L409 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | insertNode | function insertNode(p: Pos2, prev: LinkedNode) {
const node: LinkedNode = {
p: p,
prev: null,
next: null,
minX: 0,
minY: 0,
maxX: 0,
maxY: 0,
};
if (!prev) {
node.prev = node;
node.next = node;
} else {
node.next = prev.next;
node.prev = prev;
prev.next!.prev = node;
prev.next = node;
}
return node;
} | // create a new node in a doubly linked list | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L412-L433 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getSqDist | function getSqDist(p1: Pos2, p2: Pos2) {
const dx = p1[0] - p2[0],
dy = p1[1] - p2[1];
return dx * dx + dy * dy;
} | // square distance between 2 points | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L436-L441 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | sqSegDist | function sqSegDist(p: Pos2, p1: Pos2, p2: Pos2) {
let x = p1[0],
y = p1[1],
dx = p2[0] - x,
dy = p2[1] - y;
if (dx !== 0 || dy !== 0) {
const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = p2[0];
y = p2[1];
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p[0] - x;
dy = p[1] - y;
return dx * dx + dy * dy;
} | // square distance from a point to a segment | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L444-L466 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | sqSegSegDist | function sqSegSegDist(
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number,
x3: number,
y3: number
) {
const ux = x1 - x0;
const uy = y1 - y0;
const vx = x3 - x2;
const vy = y3 - y2;
const wx = x0 - x2;
const wy = y0 - y2;
const a = ux * ux + uy * uy;
const b = ux * vx + uy * vy;
const c = vx * vx + vy * vy;
const d = ux * wx + uy * wy;
const e = vx * wx + vy * wy;
const D = a * c - b * b;
let sN, tN;
let sD = D;
let tD = D;
if (D === 0) {
sN = 0;
sD = 1;
tN = e;
tD = c;
} else {
sN = b * e - c * d;
tN = a * e - b * d;
if (sN < 0) {
sN = 0;
tN = e;
tD = c;
} else if (sN > sD) {
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0.0) {
tN = 0.0;
if (-d < 0.0) sN = 0.0;
else if (-d > a) sN = sD;
else {
sN = -d;
sD = a;
}
} else if (tN > tD) {
tN = tD;
if (-d + b < 0.0) sN = 0;
else if (-d + b > a) sN = sD;
else {
sN = -d + b;
sD = a;
}
}
const sc = sN === 0 ? 0 : sN / sD;
const tc = tN === 0 ? 0 : tN / tD;
const cx = (1 - sc) * x0 + sc * x1;
const cy = (1 - sc) * y0 + sc * y1;
const cx2 = (1 - tc) * x2 + tc * x3;
const cy2 = (1 - tc) * y2 + tc * y3;
const dx = cx2 - cx;
const dy = cy2 - cy;
return dx * dx + dy * dy;
} | // segment to segment distance, ported from http://geomalgorithms.com/a07-_distance.html by Dan Sunday | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/concaveman.ts#L469-L544 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | readTags | function readTags(
tags: TagObject,
dataView: DataView,
tiffStart: number,
dirStart: number,
bigEnd: boolean
) {
const entries = dataView.getUint16(dirStart, !bigEnd);
for (let i = 0; i < entries; i++) {
const entryOffset = dirStart + i * 12 + 2;
const tag: string | number = dataView.getUint16(entryOffset, !bigEnd);
// Skip MakerNote: this is an opaque field, often binary.
if (tag === 0x927c) continue;
const key = tag in Tags ? Tags[tag] : tag;
const rawValue = readTagValue(dataView, entryOffset, tiffStart, bigEnd);
if (rawValue === null) continue;
const value =
typeof rawValue === "number" &&
StringValues[key] &&
StringValues[key][rawValue]
? StringValues[key][rawValue]
: rawValue;
tags[key] = value;
}
return tags;
} | /**
* Read the metadata tags from the file between starting/ending points.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/exif.ts#L101-L127 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | readTagValue | function readTagValue(
dataView: DataView,
entryOffset: number,
tiffStart: number,
bigEnd: boolean
): ExifValue | null {
const type = dataView.getUint16(entryOffset + 2, !bigEnd);
const numValues = dataView.getUint32(entryOffset + 4, !bigEnd);
const valueOffset = dataView.getUint32(entryOffset + 8, !bigEnd) + tiffStart;
switch (type) {
case 1: // byte, 8-bit unsigned int
case 7: // undefined, 8-bit byte, value depending on field
if (numValues === 1) {
return dataView.getUint8(entryOffset + 8);
} else {
const offset = numValues > 4 ? valueOffset : entryOffset + 8;
const vals = [];
for (let n = 0; n < numValues; n++) {
vals[n] = dataView.getUint8(offset + n);
}
return vals;
}
case 2: {
// ascii, 8-bit byte
const offset = numValues > 4 ? valueOffset : entryOffset + 8;
return getStringFromDB(dataView, offset, numValues - 1);
}
case 3: {
// short, 16 bit int
if (numValues === 1) {
return dataView.getUint16(entryOffset + 8, !bigEnd);
} else {
const offset = numValues > 2 ? valueOffset : entryOffset + 8;
const vals = [];
for (let n = 0; n < numValues; n++) {
vals[n] = dataView.getUint16(offset + 2 * n, !bigEnd);
}
return vals;
}
}
case 4: {
// long, 32 bit int
if (numValues === 1) {
return dataView.getUint32(entryOffset + 8, !bigEnd);
} else {
const vals = [];
for (let n = 0; n < numValues; n++) {
vals[n] = dataView.getUint32(valueOffset + 4 * n, !bigEnd);
}
return vals;
}
}
case 5: {
// rational = two long values, first is numerator, second is denominator
if (numValues === 1) {
const numerator = dataView.getUint32(valueOffset, !bigEnd);
const denominator = dataView.getUint32(valueOffset + 4, !bigEnd);
return numerator / denominator;
} else {
const vals = [];
for (let n = 0; n < numValues; n++) {
const numerator = dataView.getUint32(valueOffset + 8 * n, !bigEnd);
const denominator = dataView.getUint32(
valueOffset + 4 + 8 * n,
!bigEnd
);
vals[n] = numerator / denominator;
}
return vals;
}
}
case 9: {
// slong, 32 bit signed int
if (numValues === 1) {
return dataView.getInt32(entryOffset + 8, !bigEnd);
} else {
const vals = [];
for (let n = 0; n < numValues; n++) {
vals[n] = dataView.getInt32(valueOffset + 4 * n, !bigEnd);
}
return vals;
}
}
case 10: {
// signed rational, two slongs, first is numerator, second is denominator
if (numValues === 1) {
return (
dataView.getInt32(valueOffset, !bigEnd) /
dataView.getInt32(valueOffset + 4, !bigEnd)
);
} else {
const vals = [];
for (let n = 0; n < numValues; n++) {
vals[n] =
dataView.getInt32(valueOffset + 8 * n, !bigEnd) /
dataView.getInt32(valueOffset + 4 + 8 * n, !bigEnd);
}
return vals;
}
}
default: {
// console.error("Encountered an unknown type of value");
return null;
}
}
} | /**
* Get the value for a tag
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/exif.ts#L133-L245 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getStringFromDB | function getStringFromDB(buffer: DataView, start: number, length: number) {
let outstr = "";
for (let n = start; n < start + length; n++) {
outstr += String.fromCharCode(buffer.getUint8(n));
}
return outstr;
} | /* eslint-enable complexity */ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/exif.ts#L248-L254 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | readEXIFData | function readEXIFData(dataView: DataView, start: number) {
if (getStringFromDB(dataView, start, 4) !== "Exif") {
throw new Error(
"Not valid EXIF data! " + getStringFromDB(dataView, start, 4)
);
}
let bigEnd;
const tiffOffset = start + 6;
// test for TIFF validity and endianness
if (dataView.getUint16(tiffOffset) === 0x4949) {
bigEnd = false;
} else if (dataView.getUint16(tiffOffset) === 0x4d4d) {
bigEnd = true;
} else {
throw new Error("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
}
if (dataView.getUint16(tiffOffset + 2, !bigEnd) !== 0x002a) {
throw new Error("Not valid TIFF data! (no 0x002A)");
}
const firstIFDOffset = dataView.getUint32(tiffOffset + 4, !bigEnd);
if (firstIFDOffset < 0x00000008) {
throw new Error("Not valid TIFF data! (First offset less than 8)");
}
const tags: TagObject = {};
readTags(tags, dataView, tiffOffset, tiffOffset + firstIFDOffset, bigEnd);
if (tags.ExifIFDPointer) {
readTags(
tags,
dataView,
tiffOffset,
tiffOffset + (tags.ExifIFDPointer as number),
bigEnd
);
}
if (tags.GPSInfoIFDPointer) {
readTags(
tags,
dataView,
tiffOffset,
tiffOffset + (tags.GPSInfoIFDPointer as number),
bigEnd
);
}
return tags;
} | /**
* Parses TIFF, EXIF and GPS tags, and looks for a thumbnail
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/exif.ts#L259-L313 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | decode_bbox | function decode_bbox(hash_string: string) {
let isLon = true;
let maxLat = MAX_LAT;
let minLat = MIN_LAT;
let maxLon = MAX_LON;
let minLon = MIN_LON;
let mid: number;
let hashValue = 0;
for (let i = 0, l = hash_string.length; i < l; i++) {
const code = hash_string[i].toLowerCase();
hashValue = BASE32_CODES_DICT[code];
for (let bits = 4; bits >= 0; bits--) {
const bit = (hashValue >> bits) & 1;
if (isLon) {
mid = (maxLon + minLon) / 2;
if (bit === 1) {
minLon = mid;
} else {
maxLon = mid;
}
} else {
mid = (maxLat + minLat) / 2;
if (bit === 1) {
minLat = mid;
} else {
maxLat = mid;
}
}
isLon = !isLon;
}
}
return [minLat, minLon, maxLat, maxLon];
} | /**
* Decode Bounding Box
*
* Decode hashString into a bound box matches it. Data returned in a four-element array: [minlat, minlon, maxlat, maxlon]
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geohash.ts#L94-L128 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | DataSlice.readInt64 | readInt64(offset: number) {
let value = 0;
const isNegative =
(this._dataView.getUint8(offset + (this._littleEndian ? 7 : 0)) & 0x80) >
0;
let carrying = true;
for (let i = 0; i < 8; i++) {
let byte = this._dataView.getUint8(
offset + (this._littleEndian ? i : 7 - i)
);
if (isNegative) {
if (carrying) {
if (byte !== 0x00) {
byte = ~(byte - 1) & 0xff;
carrying = false;
}
} else {
byte = ~byte & 0xff;
}
}
value += byte * 256 ** i;
}
if (isNegative) {
value = -value;
}
return value;
} | // adapted from https://stackoverflow.com/a/55338384/8060591 | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geotiff/dataslice.ts#L116-L142 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | DataView64.getInt64 | getInt64(offset: number, littleEndian: boolean) {
let value = 0;
const isNegative =
(this._dataView.getUint8(offset + (littleEndian ? 7 : 0)) & 0x80) > 0;
let carrying = true;
for (let i = 0; i < 8; i++) {
let byte = this._dataView.getUint8(offset + (littleEndian ? i : 7 - i));
if (isNegative) {
if (carrying) {
if (byte !== 0x00) {
byte = ~(byte - 1) & 0xff;
carrying = false;
}
} else {
byte = ~byte & 0xff;
}
}
value += byte * 256 ** i;
}
if (isNegative) {
value = -value;
}
return value;
} | // adapted from https://stackoverflow.com/a/55338384/8060591 | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geotiff/dataview64.ts#L35-L58 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | GeoTIFF.constructor | constructor(
source: Source,
littleEndian: boolean,
bigTiff: boolean,
firstIFDOffset: number,
options = { cache: false }
) {
this.source = source;
this.littleEndian = littleEndian;
this.bigTiff = bigTiff;
this.firstIFDOffset = firstIFDOffset;
this.cache = options.cache || false;
this.ifdRequests = [];
} | /**
* @constructor
* @param source The datasource to read from.
* @param littleEndian Whether the image uses little endian.
* @param bigTiff Whether the image uses bigTIFF conventions.
* @param firstIFDOffset The numeric byte-offset from the start of the image
* to the first IFD.
* @param [options] further options.
* @param [options.cache=false] whether or not decoded tiles shall be cached.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geotiff/geotiff.ts#L224-L237 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | GeoTIFF.parseFileDirectoryAt | async parseFileDirectoryAt(offset: number): Promise<ImageFileDirectory> {
const entrySize = this.bigTiff ? 20 : 12;
const offsetSize = this.bigTiff ? 8 : 2;
let dataSlice = await this.getSlice(offset);
const numDirEntries = this.bigTiff
? dataSlice.readUint64(offset)
: dataSlice.readUint16(offset);
// if the slice does not cover the whole IFD, request a bigger slice, where the
// whole IFD fits: num of entries + n x tag length + offset to next IFD
const byteSize = numDirEntries * entrySize + (this.bigTiff ? 16 : 6);
if (!dataSlice.covers(offset, byteSize)) {
dataSlice = await this.getSlice(offset, byteSize);
}
const fileDirectory: {
[key: string]: any;
} = {};
// loop over the IFD and create a file directory object
let i = offset + (this.bigTiff ? 8 : 2);
for (
let entryCount = 0;
entryCount < numDirEntries;
i += entrySize, ++entryCount
) {
const fieldTag = dataSlice.readUint16(i);
const fieldType = dataSlice.readUint16(i + 2);
const typeCount = this.bigTiff
? dataSlice.readUint64(i + 4)
: dataSlice.readUint32(i + 4);
let fieldValues;
let value;
const fieldTypeLength = getFieldTypeLength(fieldType);
const valueOffset = i + (this.bigTiff ? 12 : 8);
// check whether the value is directly encoded in the tag or refers to a
// different external byte range
if (fieldTypeLength * typeCount <= (this.bigTiff ? 8 : 4)) {
fieldValues = getValues(dataSlice, fieldType, typeCount, valueOffset);
} else {
// resolve the reference to the actual byte range
const actualOffset = dataSlice.readOffset(valueOffset);
const length = getFieldTypeLength(fieldType) * typeCount;
// check, whether we actually cover the referenced byte range; if not,
// request a new slice of bytes to read from it
if (dataSlice.covers(actualOffset, length)) {
fieldValues = getValues(
dataSlice,
fieldType,
typeCount,
actualOffset
);
} else {
const fieldDataSlice = await this.getSlice(actualOffset, length);
fieldValues = getValues(
fieldDataSlice,
fieldType,
typeCount,
actualOffset
);
}
}
// unpack single values from the array
if (
typeCount === 1 &&
arrayFields.indexOf(fieldTag) === -1 &&
!(
fieldType === fieldTypes.RATIONAL ||
fieldType === fieldTypes.SRATIONAL
)
) {
value = fieldValues[0];
} else {
value = fieldValues;
}
// write the tags value to the file directly
fileDirectory[fieldTagNames[fieldTag]] = value;
}
const geoKeyDirectory = parseGeoKeyDirectory(fileDirectory);
const nextIFDByteOffset = dataSlice.readOffset(
offset + offsetSize + entrySize * numDirEntries
);
return new ImageFileDirectory(
fileDirectory,
geoKeyDirectory as FileDirectory,
nextIFDByteOffset
);
} | /**
* Instructs to parse an image file directory at the given file offset.
* As there is no way to ensure that a location is indeed the start of an IFD,
* this function must be called with caution (e.g only using the IFD offsets from
* the headers or other IFDs).
* @param offset the offset to parse the IFD at
* @returns the parsed IFD
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geotiff/geotiff.ts#L260-L354 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | GeoTIFF.getImage | async getImage(index = 0) {
const ifd = await this.requestIFD(index);
return new GeoTIFFImage(
ifd.fileDirectory,
ifd.geoKeyDirectory,
this.littleEndian,
this.cache,
this.source
);
} | /**
* Get the n-th internal subfile of an image. By default, the first is returned.
*
* @param [index=0] the index of the image to return.
* @returns the image at the given index
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geotiff/geotiff.ts#L398-L407 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | GeoTIFF.getImageCount | async getImageCount(): Promise<number> {
let index = 0;
// loop until we run out of IFDs
let hasNext = true;
while (hasNext) {
try {
await this.requestIFD(index);
++index;
} catch (e) {
if (e instanceof GeoTIFFImageIndexError) {
hasNext = false;
} else {
throw e;
}
}
}
return index;
} | /**
* Returns the count of the internal subfiles.
*
* @returns the number of internal subfile images
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geotiff/geotiff.ts#L414-L431 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | GeoTIFF.fromSource | static async fromSource(source: Source) {
const headerData = await source.fetch(0, 1024);
const dataView = new DataView64(headerData);
const BOM = dataView.getUint16(0, false);
let littleEndian: boolean;
if (BOM === 0x4949) {
littleEndian = true;
} else if (BOM === 0x4d4d) {
littleEndian = false;
} else {
throw new TypeError("Invalid byte order value.");
}
const magicNumber = dataView.getUint16(2, littleEndian);
let bigTiff: boolean;
if (magicNumber === 42) {
bigTiff = false;
} else if (magicNumber === 43) {
bigTiff = true;
const offsetByteSize = dataView.getUint16(4, littleEndian);
if (offsetByteSize !== 8) {
throw new Error("Unsupported offset byte-size.");
}
} else {
throw new TypeError("Invalid magic number.");
}
const firstIFDOffset = bigTiff
? dataView.getUint64(8, littleEndian)
: dataView.getUint32(4, littleEndian);
return new GeoTIFF(source, littleEndian, bigTiff, firstIFDOffset);
} | /**
* Parse a (Geo)TIFF file from the given source.
*
* @param source The source of data to parse from.
* @param options Additional options.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geotiff/geotiff.ts#L439-L471 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | GeoTIFF.close | close() {
return false;
} | /**
* Closes the underlying file buffer
* N.B. After the GeoTIFF has been completely processed it needs
* to be closed but only if it has been constructed from a file.
*/ | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/vendor/geotiff/geotiff.ts#L478-L480 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getHeaderEtag | const getHeaderEtag = (header: string | null) =>
header?.trim().replace(/^['"]|['"]$/g, ""); | // Etag/If-(Not)-Match handling | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/workers/static-data/src/index.ts#L65-L66 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
placemark | github_2023 | placemark | typescript | getHeaderEtag | const getHeaderEtag = (header: string | null) =>
header?.trim().replace(/^['"]|['"]$/g, ""); | // Etag/If-(Not)-Match handling | https://github.com/placemark/placemark/blob/2e8fa431f2134b98ec5025476d63fab54f12a1a2/workers/static/src/index.ts#L51-L52 | 2e8fa431f2134b98ec5025476d63fab54f12a1a2 |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleGenerativeAI.getGenerativeModel | getGenerativeModel(
modelParams: ModelParams,
requestOptions?: RequestOptions,
): GenerativeModel {
if (!modelParams.model) {
throw new GoogleGenerativeAIError(
`Must provide a model name. ` +
`Example: genai.getGenerativeModel({ model: 'my-model-name' })`,
);
}
return new GenerativeModel(this.apiKey, modelParams, requestOptions);
} | /**
* Gets a {@link GenerativeModel} instance for the provided model name.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/gen-ai.ts#L38-L49 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleGenerativeAI.getGenerativeModelFromCachedContent | getGenerativeModelFromCachedContent(
cachedContent: CachedContent,
modelParams?: Partial<ModelParams>,
requestOptions?: RequestOptions,
): GenerativeModel {
if (!cachedContent.name) {
throw new GoogleGenerativeAIRequestInputError(
"Cached content must contain a `name` field.",
);
}
if (!cachedContent.model) {
throw new GoogleGenerativeAIRequestInputError(
"Cached content must contain a `model` field.",
);
}
/**
* Not checking tools and toolConfig for now as it would require a deep
* equality comparison and isn't likely to be a common case.
*/
const disallowedDuplicates: Array<keyof ModelParams & keyof CachedContent> =
["model", "systemInstruction"];
for (const key of disallowedDuplicates) {
if (
modelParams?.[key] &&
cachedContent[key] &&
modelParams?.[key] !== cachedContent[key]
) {
if (key === "model") {
const modelParamsComp = modelParams.model.startsWith("models/")
? modelParams.model.replace("models/", "")
: modelParams.model;
const cachedContentComp = cachedContent.model.startsWith("models/")
? cachedContent.model.replace("models/", "")
: cachedContent.model;
if (modelParamsComp === cachedContentComp) {
continue;
}
}
throw new GoogleGenerativeAIRequestInputError(
`Different value for "${key}" specified in modelParams` +
` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`,
);
}
}
const modelParamsFromCache: ModelParams = {
...modelParams,
model: cachedContent.model,
tools: cachedContent.tools,
toolConfig: cachedContent.toolConfig,
systemInstruction: cachedContent.systemInstruction,
cachedContent,
};
return new GenerativeModel(
this.apiKey,
modelParamsFromCache,
requestOptions,
);
} | /**
* Creates a {@link GenerativeModel} instance from provided content cache.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/gen-ai.ts#L54-L114 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | ChatSession.getHistory | async getHistory(): Promise<Content[]> {
await this._sendPromise;
return this._history;
} | /**
* Gets the chat history so far. Blocked prompts are not added to history.
* Blocked candidates are not added to history, nor are the prompts that
* generated them.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/methods/chat-session.ts#L67-L70 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | ChatSession.sendMessage | async sendMessage(
request: string | Array<string | Part>,
requestOptions: SingleRequestOptions = {},
): Promise<GenerateContentResult> {
await this._sendPromise;
const newContent = formatNewContent(request);
const generateContentRequest: GenerateContentRequest = {
safetySettings: this.params?.safetySettings,
generationConfig: this.params?.generationConfig,
tools: this.params?.tools,
toolConfig: this.params?.toolConfig,
systemInstruction: this.params?.systemInstruction,
cachedContent: this.params?.cachedContent,
contents: [...this._history, newContent],
};
const chatSessionRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
let finalResult;
// Add onto the chain.
this._sendPromise = this._sendPromise
.then(() =>
generateContent(
this._apiKey,
this.model,
generateContentRequest,
chatSessionRequestOptions,
),
)
.then((result) => {
if (
result.response.candidates &&
result.response.candidates.length > 0 &&
result.response.candidates[0]?.content !== undefined
) {
this._history.push(newContent);
const responseContent: Content = {
parts: [],
// Response seems to come back without a role set.
role: "model",
...result.response.candidates?.[0].content,
};
this._history.push(responseContent);
} else {
const blockErrorMessage = formatBlockErrorMessage(result.response);
if (blockErrorMessage) {
console.warn(
`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`,
);
}
}
finalResult = result;
});
await this._sendPromise;
return finalResult;
} | /**
* Sends a chat message and receives a non-streaming
* {@link GenerateContentResult}.
*
* Fields set in the optional {@link SingleRequestOptions} parameter will
* take precedence over the {@link RequestOptions} values provided to
* {@link GoogleGenerativeAI.getGenerativeModel }.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/methods/chat-session.ts#L80-L136 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | ChatSession.sendMessageStream | async sendMessageStream(
request: string | Array<string | Part>,
requestOptions: SingleRequestOptions = {},
): Promise<GenerateContentStreamResult> {
await this._sendPromise;
const newContent = formatNewContent(request);
const generateContentRequest: GenerateContentRequest = {
safetySettings: this.params?.safetySettings,
generationConfig: this.params?.generationConfig,
tools: this.params?.tools,
toolConfig: this.params?.toolConfig,
systemInstruction: this.params?.systemInstruction,
cachedContent: this.params?.cachedContent,
contents: [...this._history, newContent],
};
const chatSessionRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
const streamPromise = generateContentStream(
this._apiKey,
this.model,
generateContentRequest,
chatSessionRequestOptions,
);
// Add onto the chain.
this._sendPromise = this._sendPromise
.then(() => streamPromise)
// This must be handled to avoid unhandled rejection, but jump
// to the final catch block with a label to not log this error.
.catch((_ignored) => {
throw new Error(SILENT_ERROR);
})
.then((streamResult) => streamResult.response)
.then((response) => {
if (
response.candidates &&
response.candidates.length > 0 &&
response.candidates[0]?.content !== undefined
) {
this._history.push(newContent);
const responseContent = { ...response.candidates[0].content };
// Response seems to come back without a role set.
if (!responseContent.role) {
responseContent.role = "model";
}
this._history.push(responseContent);
} else {
const blockErrorMessage = formatBlockErrorMessage(response);
if (blockErrorMessage) {
console.warn(
`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`,
);
}
}
})
.catch((e) => {
// Errors in streamPromise are already catchable by the user as
// streamPromise is returned.
// Avoid duplicating the error message in logs.
if (e.message !== SILENT_ERROR) {
// Users do not have access to _sendPromise to catch errors
// downstream from streamPromise, so they should not throw.
console.error(e);
}
});
return streamPromise;
} | /**
* Sends a chat message and receives the response as a
* {@link GenerateContentStreamResult} containing an iterable stream
* and a response promise.
*
* Fields set in the optional {@link SingleRequestOptions} parameter will
* take precedence over the {@link RequestOptions} values provided to
* {@link GoogleGenerativeAI.getGenerativeModel }.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/methods/chat-session.ts#L147-L215 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GenerativeModel.generateContent | async generateContent(
request: GenerateContentRequest | string | Array<string | Part>,
requestOptions: SingleRequestOptions = {},
): Promise<GenerateContentResult> {
const formattedParams = formatGenerateContentInput(request);
const generativeModelRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
return generateContent(
this.apiKey,
this.model,
{
generationConfig: this.generationConfig,
safetySettings: this.safetySettings,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
cachedContent: this.cachedContent?.name,
...formattedParams,
},
generativeModelRequestOptions,
);
} | /**
* Makes a single non-streaming call to the model
* and returns an object containing a single {@link GenerateContentResponse}.
*
* Fields set in the optional {@link SingleRequestOptions} parameter will
* take precedence over the {@link RequestOptions} values provided to
* {@link GoogleGenerativeAI.getGenerativeModel }.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/models/generative-model.ts#L97-L120 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GenerativeModel.generateContentStream | async generateContentStream(
request: GenerateContentRequest | string | Array<string | Part>,
requestOptions: SingleRequestOptions = {},
): Promise<GenerateContentStreamResult> {
const formattedParams = formatGenerateContentInput(request);
const generativeModelRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
return generateContentStream(
this.apiKey,
this.model,
{
generationConfig: this.generationConfig,
safetySettings: this.safetySettings,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
cachedContent: this.cachedContent?.name,
...formattedParams,
},
generativeModelRequestOptions,
);
} | /**
* Makes a single streaming call to the model and returns an object
* containing an iterable stream that iterates over all chunks in the
* streaming response as well as a promise that returns the final
* aggregated response.
*
* Fields set in the optional {@link SingleRequestOptions} parameter will
* take precedence over the {@link RequestOptions} values provided to
* {@link GoogleGenerativeAI.getGenerativeModel }.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/models/generative-model.ts#L132-L155 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GenerativeModel.startChat | startChat(startChatParams?: StartChatParams): ChatSession {
return new ChatSession(
this.apiKey,
this.model,
{
generationConfig: this.generationConfig,
safetySettings: this.safetySettings,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
cachedContent: this.cachedContent?.name,
...startChatParams,
},
this._requestOptions,
);
} | /**
* Gets a new {@link ChatSession} instance which can be used for
* multi-turn chats.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/models/generative-model.ts#L161-L176 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GenerativeModel.countTokens | async countTokens(
request: CountTokensRequest | string | Array<string | Part>,
requestOptions: SingleRequestOptions = {},
): Promise<CountTokensResponse> {
const formattedParams = formatCountTokensInput(request, {
model: this.model,
generationConfig: this.generationConfig,
safetySettings: this.safetySettings,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
cachedContent: this.cachedContent,
});
const generativeModelRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
return countTokens(
this.apiKey,
this.model,
formattedParams,
generativeModelRequestOptions,
);
} | /**
* Counts the tokens in the provided request.
*
* Fields set in the optional {@link SingleRequestOptions} parameter will
* take precedence over the {@link RequestOptions} values provided to
* {@link GoogleGenerativeAI.getGenerativeModel }.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/models/generative-model.ts#L185-L208 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GenerativeModel.embedContent | async embedContent(
request: EmbedContentRequest | string | Array<string | Part>,
requestOptions: SingleRequestOptions = {},
): Promise<EmbedContentResponse> {
const formattedParams = formatEmbedContentInput(request);
const generativeModelRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
return embedContent(
this.apiKey,
this.model,
formattedParams,
generativeModelRequestOptions,
);
} | /**
* Embeds the provided content.
*
* Fields set in the optional {@link SingleRequestOptions} parameter will
* take precedence over the {@link RequestOptions} values provided to
* {@link GoogleGenerativeAI.getGenerativeModel }.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/models/generative-model.ts#L217-L232 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GenerativeModel.batchEmbedContents | async batchEmbedContents(
batchEmbedContentRequest: BatchEmbedContentsRequest,
requestOptions: SingleRequestOptions = {},
): Promise<BatchEmbedContentsResponse> {
const generativeModelRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
return batchEmbedContents(
this.apiKey,
this.model,
batchEmbedContentRequest,
generativeModelRequestOptions,
);
} | /**
* Embeds an array of {@link EmbedContentRequest}s.
*
* Fields set in the optional {@link SingleRequestOptions} parameter will
* take precedence over the {@link RequestOptions} values provided to
* {@link GoogleGenerativeAI.getGenerativeModel }.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/models/generative-model.ts#L241-L255 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | assignRoleToPartsAndValidateSendMessageRequest | function assignRoleToPartsAndValidateSendMessageRequest(
parts: Part[],
): Content {
const userContent: Content = { role: "user", parts: [] };
const functionContent: Content = { role: "function", parts: [] };
let hasUserContent = false;
let hasFunctionContent = false;
for (const part of parts) {
if ("functionResponse" in part) {
functionContent.parts.push(part);
hasFunctionContent = true;
} else {
userContent.parts.push(part);
hasUserContent = true;
}
}
if (hasUserContent && hasFunctionContent) {
throw new GoogleGenerativeAIError(
"Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.",
);
}
if (!hasUserContent && !hasFunctionContent) {
throw new GoogleGenerativeAIError(
"No content is provided for sending chat message.",
);
}
if (hasUserContent) {
return userContent;
}
return functionContent;
} | /**
* When multiple Part types (i.e. FunctionResponsePart and TextPart) are
* passed in a single Part array, we may need to assign different roles to each
* part. Currently only FunctionResponsePart requires a role other than 'user'.
* @private
* @param parts Array of parts to pass to the model
* @returns Array of content items
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/requests/request-helpers.ts#L78-L112 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | buildFetchOptions | function buildFetchOptions(requestOptions?: SingleRequestOptions): RequestInit {
const fetchOptions = {} as RequestInit;
if (requestOptions?.signal !== undefined || requestOptions?.timeout >= 0) {
const controller = new AbortController();
if (requestOptions?.timeout >= 0) {
setTimeout(() => controller.abort(), requestOptions.timeout);
}
if (requestOptions?.signal) {
requestOptions.signal.addEventListener("abort", () => {
controller.abort();
});
}
fetchOptions.signal = controller.signal;
}
return fetchOptions;
} | /**
* Generates the request options to be passed to the fetch API.
* @param requestOptions - The user-defined request options.
* @returns The generated request options.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/requests/request.ts#L220-L235 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAICacheManager.create | async create(
createOptions: CachedContentCreateParams,
): Promise<CachedContent> {
const newCachedContent: CachedContent = { ...createOptions };
if (createOptions.ttlSeconds) {
if (createOptions.expireTime) {
throw new GoogleGenerativeAIRequestInputError(
"You cannot specify both `ttlSeconds` and `expireTime` when creating" +
" a content cache. You must choose one.",
);
}
if (createOptions.systemInstruction) {
newCachedContent.systemInstruction = formatSystemInstruction(
createOptions.systemInstruction,
);
}
newCachedContent.ttl = createOptions.ttlSeconds.toString() + "s";
delete (newCachedContent as CachedContentCreateParams).ttlSeconds;
}
if (!newCachedContent.model) {
throw new GoogleGenerativeAIRequestInputError(
"Cached content must contain a `model` field.",
);
}
if (!newCachedContent.model.includes("/")) {
// If path is not included, assume it's a non-tuned model.
newCachedContent.model = `models/${newCachedContent.model}`;
}
const url = new CachedContentUrl(
RpcTask.CREATE,
this.apiKey,
this._requestOptions,
);
const headers = getHeaders(url);
const response = await makeServerRequest(
url,
headers,
JSON.stringify(newCachedContent),
);
return response.json();
} | /**
* Upload a new content cache
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/cache-manager.ts#L47-L89 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAICacheManager.list | async list(listParams?: ListParams): Promise<ListCacheResponse> {
const url = new CachedContentUrl(
RpcTask.LIST,
this.apiKey,
this._requestOptions,
);
if (listParams?.pageSize) {
url.appendParam("pageSize", listParams.pageSize.toString());
}
if (listParams?.pageToken) {
url.appendParam("pageToken", listParams.pageToken);
}
const headers = getHeaders(url);
const response = await makeServerRequest(url, headers);
return response.json();
} | /**
* List all uploaded content caches
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/cache-manager.ts#L94-L109 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAICacheManager.get | async get(name: string): Promise<CachedContent> {
const url = new CachedContentUrl(
RpcTask.GET,
this.apiKey,
this._requestOptions,
);
url.appendPath(parseCacheName(name));
const headers = getHeaders(url);
const response = await makeServerRequest(url, headers);
return response.json();
} | /**
* Get a content cache
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/cache-manager.ts#L114-L124 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAICacheManager.update | async update(
name: string,
updateParams: CachedContentUpdateParams,
): Promise<CachedContent> {
const url = new CachedContentUrl(
RpcTask.UPDATE,
this.apiKey,
this._requestOptions,
);
url.appendPath(parseCacheName(name));
const headers = getHeaders(url);
const formattedCachedContent: _CachedContentUpdateRequestFields = {
...updateParams.cachedContent,
};
if (updateParams.cachedContent.ttlSeconds) {
formattedCachedContent.ttl =
updateParams.cachedContent.ttlSeconds.toString() + "s";
delete (formattedCachedContent as CachedContentCreateParams).ttlSeconds;
}
if (updateParams.updateMask) {
url.appendParam(
"update_mask",
updateParams.updateMask.map((prop) => camelToSnake(prop)).join(","),
);
}
const response = await makeServerRequest(
url,
headers,
JSON.stringify(formattedCachedContent),
);
return response.json();
} | /**
* Update an existing content cache
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/cache-manager.ts#L129-L160 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAICacheManager.delete | async delete(name: string): Promise<void> {
const url = new CachedContentUrl(
RpcTask.DELETE,
this.apiKey,
this._requestOptions,
);
url.appendPath(parseCacheName(name));
const headers = getHeaders(url);
await makeServerRequest(url, headers);
} | /**
* Delete content cache with given name
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/cache-manager.ts#L165-L174 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | parseCacheName | function parseCacheName(name: string): string {
if (name.startsWith("cachedContents/")) {
return name.split("cachedContents/")[1];
}
if (!name) {
throw new GoogleGenerativeAIError(
`Invalid name ${name}. ` +
`Must be in the format "cachedContents/name" or "name"`,
);
}
return name;
} | /**
* If cache name is prepended with "cachedContents/", remove prefix
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/cache-manager.ts#L180-L191 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAIFileManager.uploadFile | async uploadFile(
filePath: string,
fileMetadata: FileMetadata,
): Promise<UploadFileResponse> {
const file = readFileSync(filePath);
const url = new FilesRequestUrl(
RpcTask.UPLOAD,
this.apiKey,
this._requestOptions,
);
const uploadHeaders = getHeaders(url);
const boundary = generateBoundary();
uploadHeaders.append("X-Goog-Upload-Protocol", "multipart");
uploadHeaders.append(
"Content-Type",
`multipart/related; boundary=${boundary}`,
);
const uploadMetadata = getUploadMetadata(fileMetadata);
// Multipart formatting code taken from @firebase/storage
const metadataString = JSON.stringify({ file: uploadMetadata });
const preBlobPart =
"--" +
boundary +
"\r\n" +
"Content-Type: application/json; charset=utf-8\r\n\r\n" +
metadataString +
"\r\n--" +
boundary +
"\r\n" +
"Content-Type: " +
fileMetadata.mimeType +
"\r\n\r\n";
const postBlobPart = "\r\n--" + boundary + "--";
const blob = new Blob([preBlobPart, file, postBlobPart]);
const response = await makeServerRequest(url, uploadHeaders, blob);
return response.json();
} | /**
* Upload a file.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/file-manager.ts#L53-L93 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAIFileManager.listFiles | async listFiles(
listParams?: ListParams,
requestOptions: SingleRequestOptions = {},
): Promise<ListFilesResponse> {
const filesRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
const url = new FilesRequestUrl(
RpcTask.LIST,
this.apiKey,
filesRequestOptions,
);
if (listParams?.pageSize) {
url.appendParam("pageSize", listParams.pageSize.toString());
}
if (listParams?.pageToken) {
url.appendParam("pageToken", listParams.pageToken);
}
const uploadHeaders = getHeaders(url);
const response = await makeServerRequest(url, uploadHeaders);
return response.json();
} | /**
* List all uploaded files.
*
* Any fields set in the optional {@link SingleRequestOptions} parameter will take
* precedence over the {@link RequestOptions} values provided at the time of the
* {@link GoogleAIFileManager} initialization.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/file-manager.ts#L102-L124 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAIFileManager.getFile | async getFile(
fileId: string,
requestOptions: SingleRequestOptions = {},
): Promise<FileMetadataResponse> {
const filesRequestOptions: SingleRequestOptions = {
...this._requestOptions,
...requestOptions,
};
const url = new FilesRequestUrl(
RpcTask.GET,
this.apiKey,
filesRequestOptions,
);
url.appendPath(parseFileId(fileId));
const uploadHeaders = getHeaders(url);
const response = await makeServerRequest(url, uploadHeaders);
return response.json();
} | /**
* Get metadata for file with given ID.
*
* Any fields set in the optional {@link SingleRequestOptions} parameter will take
* precedence over the {@link RequestOptions} values provided at the time of the
* {@link GoogleAIFileManager} initialization.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/file-manager.ts#L133-L150 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | GoogleAIFileManager.deleteFile | async deleteFile(fileId: string): Promise<void> {
const url = new FilesRequestUrl(
RpcTask.DELETE,
this.apiKey,
this._requestOptions,
);
url.appendPath(parseFileId(fileId));
const uploadHeaders = getHeaders(url);
await makeServerRequest(url, uploadHeaders);
} | /**
* Delete file with given ID.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/file-manager.ts#L155-L164 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | parseFileId | function parseFileId(fileId: string): string {
if (fileId.startsWith("files/")) {
return fileId.split("files/")[1];
}
if (!fileId) {
throw new GoogleGenerativeAIError(
`Invalid fileId ${fileId}. ` +
`Must be in the format "files/filename" or "filename"`,
);
}
return fileId;
} | /**
* If fileId is prepended with "files/", remove prefix
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/file-manager.ts#L170-L182 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
generative-ai-js | github_2023 | google-gemini | typescript | getSignal | function getSignal(requestOptions?: SingleRequestOptions): AbortSignal | null {
if (requestOptions?.signal !== undefined || requestOptions?.timeout >= 0) {
const controller = new AbortController();
if (requestOptions?.timeout >= 0) {
setTimeout(() => controller.abort(), requestOptions.timeout);
}
if (requestOptions.signal) {
requestOptions.signal.addEventListener("abort", () => {
controller.abort();
});
}
return controller.signal;
}
} | /**
* Create an AbortSignal based on the timeout and signal in the
* RequestOptions.
*/ | https://github.com/google-gemini/generative-ai-js/blob/2df2af03bb07dcda23b07af1a7135a8b461ae64e/src/server/request.ts#L124-L137 | 2df2af03bb07dcda23b07af1a7135a8b461ae64e |
dokemon | github_2023 | productiveops | typescript | apiPost | function apiPost(url: string, body: any) {
return fetch(url, {
method: "POST",
...commonOptions,
body: body ? JSON.stringify(body) : null,
})
} | // Common | https://github.com/productiveops/dokemon/blob/e800d3e62bc4efed59d9058998bad7f15660d851/web/src/lib/api.ts#L48-L54 | e800d3e62bc4efed59d9058998bad7f15660d851 |
headscale-admin | github_2023 | GoodiesHQ | typescript | StateLocal.key | get key() {
return this.#key;
} | // #saver = $derived(this.save(this.#value)) | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/States.svelte.ts#L50-L52 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.stripPrefix | private static stripPrefix(name: string): string {
const nameLower = name.toLowerCase()
for (const prefix of Object.values(Prefixes)) {
if (nameLower.startsWith(prefix)) {
return name.substring(prefix.length)
}
}
return name
} | // remove the group: prefix if it exists | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L107-L115 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.validateGroupName | static validateGroupName(name: string): string {
name = this.stripPrefix(name)
if (name.toLowerCase() !== name) {
throw new Error("Group name must be lowercase")
}
if (!RegexGroupName.test(name)) {
throw new Error("Group name is limited to: lowercase alphabet, digits, dashes, and periods")
}
return name
} | // throws an error if the name is invalid, otherwise returns the normalized group name | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L136-L145 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.validateTagName | static validateTagName(name: string): string {
name = this.stripPrefix(name)
if (!RegexTagName.test(name)) {
throw new Error("Tag name must contain no spaces")
}
return name
} | // tag names can contain anything but spaces | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L148-L154 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.validateHostName | static validateHostName(name: string): string {
name = name.toLowerCase()
if (!RegexHostName.test(name)) {
throw new Error("Host name is limited to: lowercase alphabet, digits, dashes, and periods")
}
return name
} | // host names can contain anything but spaces | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L157-L163 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.clone | clone(): ACLBuilder {
return JSON.parse(JSON.stringify(this)) as ACLBuilder
} | // deep clone of current ACL | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L176-L178 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.createHost | createHost(name: string, cidr: string) {
if(this.getHostCIDR(name) !== undefined) {
throw new Error(`host "${name}" already exists`)
}
this.setHost(name, cidr)
} | /*
* Host:
* --------------------------------
* createHost(name, cidr)
* getHostCIDR(name)
* setHost(name, cidr)
* renameHost(nameOld, nameNew)
* getHostNames() string[]
* getHosts(name) [string, string][]
* hostExists(name)
* deleteHost(name)
*/ | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L194-L199 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.createTag | createTag(name: string) {
name = ACLBuilder.validateTagName(name)
const { prefixed } = ACLBuilder.normalizePrefix(name, 'tag')
this.tagOwners[prefixed] = []
} | /*
* Tags:
* --------------------------------
* createTag(name)
* renameTag(nameOld, nameNew)
* setTagOwners(name, members[])
* getTagNames() string[]
* getTagOwners(name) [string, string[]]
* getTagOwnersTyped(name) {users: string[], groups: string[]}
* tagExists(name)
* deleteTag(name)
*/ | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L277-L281 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.createGroup | createGroup(name: string) {
name = ACLBuilder.validateGroupName(name)
const { stripped, prefixed } = ACLBuilder.normalizePrefix(name, 'group')
if (this.groups[prefixed] !== undefined) {
throw new Error(`Group '${stripped}' already exists`)
}
this.groups[prefixed] = []
} | /*
* GROUPS:
* --------------------------------
* createGroup(name)
* renameGroup(nameOld, nameNew)
* setGroupMembers(name, members[])
* getGroupNames() string[]
* getGroupMembers(name)
* groupExists(name)
* deleteGroup(name)
*/ | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L405-L414 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.getPolicyDstHost | public static getPolicyDstHost(dst: string): string {
const i = dst.lastIndexOf(':')
return i < 0 ? dst : dst.substring(0, i)
} | /*
* POLICIES:
* --------------------------------
* createPolicy(policy)
* getAllPolicies()
* getPolicy(idx)
* setPolicy(idx, policy)
* delPolicy(idx)
* setPolicySrc(idx, src)
* setPolicyDst(idx, dst)
* setPolicyProto(idx, proto)
*/ | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L525-L528 | 45294af1be374bf20c7395934a7923c303c1dca6 |
headscale-admin | github_2023 | GoodiesHQ | typescript | ACLBuilder.createSshRule | createSshRule(rule: AclSshRule) {
if (this.ssh === undefined){
this.ssh = []
}
this.ssh.push(rule)
} | /*
* SSH Rules:
* --------------------------------
* createSshRule(rule)
* getAllPolicies()
* getPolicy(idx)
* setPolicy(idx, policy)
* delPolicy(idx)
* setPolicySrc(idx, src)
* setPolicyDst(idx, dst)
* setPolicyProto(idx, proto)
*/ | https://github.com/GoodiesHQ/headscale-admin/blob/45294af1be374bf20c7395934a7923c303c1dca6/src/lib/common/acl.svelte.ts#L607-L612 | 45294af1be374bf20c7395934a7923c303c1dca6 |
tsdiagram | github_2023 | 3rd | typescript | toPoint | const toPoint = ([x, y]: number[]): XYPosition => ({ x, y }); | // import { edgeSegmentCache } from "../../edge-segment-cache"; | https://github.com/3rd/tsdiagram/blob/7a7511ccae77b7287c7bec13ced791052da7aec5/src/components/Renderer/CustomEdge.tsx#L9-L9 | 7a7511ccae77b7287c7bec13ced791052da7aec5 |
tsdiagram | github_2023 | 3rd | typescript | getDirection | const getDirection = (a: XYPosition, b: XYPosition) => {
if (a.x === b.x) {
if (a.y > b.y) return Direction.Top;
return Direction.Bottom;
} else if (a.y === b.y) {
if (a.x > b.x) return Direction.Left;
return Direction.Right;
}
return Direction.None;
}; | // const toXYPosition = ({ x, y }: XYPosition): [number, number] => [x, y]; | https://github.com/3rd/tsdiagram/blob/7a7511ccae77b7287c7bec13ced791052da7aec5/src/components/Renderer/CustomEdge.tsx#L12-L21 | 7a7511ccae77b7287c7bec13ced791052da7aec5 |
tsdiagram | github_2023 | 3rd | typescript | ModelParser.getModels | getModels() {
const models: Model[] = [];
const modelNameToModelMap = new Map<string, Model>();
const dependencyMap = new Map<string, Set<Model>>();
// first pass: build nodes and models
const items: ((
| { type: "class"; model: ClassModel; node: ParsedClass }
| { type: "interface"; model: InterfaceModel; node: ParsedInterface }
| { type: "typeAlias"; model: TypeAliasModel; node: ParsedTypeAlias }
) & { id: string; name: string; compilerType: ts.Type })[] = [];
for (const _interface of this.interfaces) {
const name = sanitizePropertyName(_interface.name);
const compilerType = _interface.declaration.getType().compilerType;
const model: InterfaceModel = {
id: name,
name,
extends: [],
schema: [],
dependencies: [],
dependants: [],
type: "interface",
arguments: [],
};
for (const parameter of _interface.declaration.getTypeParameters()) {
const parameterName = sanitizePropertyName(parameter.getName());
const parameterType = parameter.getType();
const parameterExtends = parameterType.getConstraint()?.getText();
model.arguments.push({ name: parameterName, extends: parameterExtends });
}
for (const extendsExpression of _interface.extends) {
const extendsName = trimImport(extendsExpression.getText());
const extendsModel = modelNameToModelMap.get(extendsName);
if (extendsModel) {
model.extends.push(extendsModel);
} else model.extends.push(extendsName);
}
models.push(model);
modelNameToModelMap.set(model.id, model);
items.push({
type: "interface",
id: name,
name,
node: _interface,
compilerType,
model,
});
}
for (const typeAlias of this.typeAliases) {
const name = sanitizePropertyName(typeAlias.name);
const type = typeAlias.declaration.getType().compilerType;
const model: TypeAliasModel = {
id: name,
name,
schema: [],
dependencies: [],
dependants: [],
type: "typeAlias",
arguments: [],
};
for (const parameter of typeAlias.declaration.getTypeParameters()) {
const parameterName = sanitizePropertyName(parameter.getName());
const parameterType = parameter.getType();
const parameterExtends = parameterType.getConstraint()?.getText();
model.arguments.push({ name: parameterName, extends: parameterExtends });
}
models.push(model);
modelNameToModelMap.set(model.id, model);
items.push({
type: "typeAlias",
id: name,
name,
node: typeAlias,
compilerType: type,
model,
});
}
for (const currentClass of this.classes) {
const name = sanitizePropertyName(currentClass.name);
const type = currentClass.declaration.getType().compilerType;
const model: ClassModel = {
id: name,
name,
implements: [],
schema: [],
dependencies: [],
dependants: [],
type: "class",
arguments: [],
};
for (const parameter of currentClass.declaration.getTypeParameters()) {
const parameterName = sanitizePropertyName(parameter.getName());
const parameterType = parameter.getType();
const parameterExtends = parameterType.getConstraint()?.getText();
model.arguments.push({ name: parameterName, extends: parameterExtends });
}
if (currentClass.extends) {
const extendsName = sanitizePropertyName(trimImport(currentClass.extends.getText()));
const extendsModel = modelNameToModelMap.get(extendsName);
if (extendsModel) {
model.extends = extendsModel;
} else model.extends = extendsName;
}
if (currentClass.implements.length > 0) {
for (const implementsExpression of currentClass.implements) {
const implementsName = sanitizePropertyName(trimImport(implementsExpression.getText()));
const implementsModel = modelNameToModelMap.get(implementsName);
model.implements.push(implementsModel ?? implementsName);
}
}
models.push(model);
modelNameToModelMap.set(model.id, model);
items.push({
type: "class",
id: name,
name,
node: currentClass,
compilerType: type,
model,
});
}
// second pass: parse schema and root dependencies
for (const item of items) {
const model = modelNameToModelMap.get(item.name);
if (!model) continue;
const dependencies = dependencyMap.get(item.name) ?? new Set<Model>();
// helpers
const addFunctionProp = (prop: Prop, type?: Type) => {
const propName = sanitizePropertyName(prop.getName());
const propType = type ?? prop.getType();
const callSignatures = propType.getCallSignatures();
if (callSignatures.length === 1) {
const callSignature = callSignatures[0];
const functionArguments: { name: string; type: Model | string }[] = [];
for (const parameter of callSignature.getParameters()) {
const parameterName = sanitizePropertyName(parameter.getName());
const parameterTypeName = trimImport(parameter.getTypeAtLocation(prop).getText());
const parameterTypeModel = modelNameToModelMap.get(parameterTypeName);
if (parameterTypeModel) dependencies.add(parameterTypeModel);
functionArguments.push({
name: parameterName,
type: parameterTypeModel ?? parameterTypeName,
});
}
const returnType = callSignature.getReturnType();
const isArray = returnType.isArray();
const returnTypeName = isArray
? trimImport(returnType.getArrayElementType()?.getText() ?? "")
: trimImport(returnType.getText());
const returnTypeModel = modelNameToModelMap.get(returnTypeName);
if (returnTypeModel) dependencies.add(returnTypeModel);
let optional = false;
if (prop.isKind?.(ts.SyntaxKind.PropertySignature)) {
optional = prop.hasQuestionToken();
}
model.schema.push({
name: propName,
type: "function",
arguments: functionArguments,
returnType: isArray ? [returnTypeModel ?? returnTypeName] : returnTypeModel ?? returnTypeName,
optional,
});
return true;
}
return false;
};
const addArrayProp = (prop: Prop, type?: Type) => {
const propName = sanitizePropertyName(prop.getName());
const propType = type ?? prop.getType();
if (!propType.isArray()) return false;
const elementType = prop.getType().getArrayElementType();
if (!elementType) return false;
const elementTypeName = trimImport(elementType.getText());
const elementTypeModel = modelNameToModelMap.get(elementTypeName);
let optional = false;
if (prop.isKind(ts.SyntaxKind.PropertySignature)) {
optional = prop.hasQuestionToken();
}
model.schema.push({
name: propName,
type: "array",
elementType: elementTypeModel ?? elementTypeName,
optional,
});
if (elementTypeModel) dependencies.add(elementTypeModel);
return true;
};
const addGenericProp = (prop: Prop, type?: Type) => {
const propName = sanitizePropertyName(prop.getName());
const propType = type ?? prop.getType();
const aliasSymbol = propType.getAliasSymbol();
const symbol = aliasSymbol ?? propType.getSymbol();
const typeArguments = aliasSymbol ? propType.getAliasTypeArguments() : propType.getTypeArguments();
const typeNode =
"getTypeNode" in prop ? (prop.getTypeNode() as TypeReferenceNode | undefined) : undefined;
const typeNodeArguments = typeNode?.isKind(ts.SyntaxKind.TypeReference)
? typeNode.getTypeArguments()
: [];
if (symbol && typeArguments.length > 0) {
const genericName = symbol.getName();
if (!genericName) return false;
const genericModel = modelNameToModelMap.get(genericName);
if (genericModel) dependencies.add(genericModel);
let optional = false;
if (prop.isKind(ts.SyntaxKind.PropertySignature)) {
optional = prop.hasQuestionToken();
}
const schemaField: GenericSchemaField = {
name: propName,
type: "generic",
genericName,
arguments: [],
optional,
};
for (const [i, typeArgument] of typeArguments.entries()) {
let typeArgumentName = trimImport(typeArgument.getText());
if (typeNodeArguments[i] && typeNodeArguments[i].isKind(ts.SyntaxKind.TypeReference)) {
typeArgumentName = trimImport(typeNodeArguments[i].getText());
}
const typeArgumentModel = modelNameToModelMap.get(typeArgumentName);
schemaField.arguments.push(typeArgumentModel ?? typeArgumentName);
if (typeArgumentModel) dependencies.add(typeArgumentModel);
}
model.schema.push(schemaField);
return true;
}
return false;
};
// FIXME: type these functions, prop is Symbol when Type is provided
const addDefaultProp = (prop: Prop, type?: Type) => {
const propName = sanitizePropertyName(prop.getName());
const propType = type ?? prop.getType();
let typeName = trimImport(propType.getText());
const symbolDeclaration = prop.getSymbol?.()?.getDeclarations()?.[0];
if (symbolDeclaration?.isKind(ts.SyntaxKind.PropertySignature)) {
const declarationName = symbolDeclaration.getTypeNode()?.getText();
if (declarationName) typeName = trimImport(declarationName);
}
const typeModel = modelNameToModelMap.get(typeName);
if (typeModel) dependencies.add(typeModel);
let optional = false;
if (
prop.isKind?.(ts.SyntaxKind.PropertySignature) ||
prop.isKind?.(ts.SyntaxKind.PropertyDeclaration)
) {
optional = prop.hasQuestionToken();
}
model.schema.push({
name: propName,
type: typeModel ?? typeName,
optional,
});
};
if (item.type === "typeAlias") {
if (
[
//
item.node.type.isNumber(),
item.node.type.isString(),
item.node.type.isBoolean(),
item.node.type.isUndefined(),
item.node.type.isNull(),
item.node.type.isAny(),
item.node.type.isUnknown(),
item.node.type.isNever(),
item.node.type.isEnum(),
item.node.type.isEnumLiteral(),
item.node.type.isLiteral(),
].some(Boolean)
) {
model.schema.push({ name: "==>", type: item.node.type.getText(), optional: false });
continue;
}
if (item.node.type.isUnion()) {
const types: (Model | ({} & string))[] = [];
for (const type of item.node.type.getUnionTypes()) {
const typeName = trimImport(type.getText());
const typeModel = modelNameToModelMap.get(typeName);
if (typeModel) dependencies.add(typeModel);
types.push(typeModel ?? typeName);
}
model.schema.push({ name: "==>", type: "union", types, optional: false });
dependencyMap.set(item.name, dependencies);
continue;
}
const typeAtLocation = this.checker.getTypeAtLocation(item.node.declaration);
for (const prop of typeAtLocation.getProperties()) {
const valueDeclaration = prop.getValueDeclaration() as PropertyDeclaration | undefined;
if (valueDeclaration) {
if (addFunctionProp(valueDeclaration)) continue;
if (addArrayProp(valueDeclaration)) continue;
if (addGenericProp(valueDeclaration)) continue;
addDefaultProp(valueDeclaration);
} else {
const propType = this.checker.getTypeOfSymbolAtLocation(prop, item.node.declaration);
// @ts-expect-error
if (addFunctionProp(prop as unknown, propType)) continue;
// @ts-expect-error
if (addArrayProp(prop as unknown, propType)) continue;
// @ts-expect-error
if (addGenericProp(prop as unknown, propType)) continue;
// @ts-expect-error
addDefaultProp(prop as unknown, propType);
}
}
}
if (item.type === "interface") {
for (const extended of item.node.extends) {
const extendsName = trimImport(extended.getText());
const extendsModel = modelNameToModelMap.get(extendsName);
if (extendsModel) dependencies.add(extendsModel);
}
for (const prop of [
...item.node.members,
...item.node.declaration.getGetAccessors(),
...item.node.declaration.getSetAccessors(),
]) {
if (addFunctionProp(prop)) continue;
if (addArrayProp(prop)) continue;
if (addGenericProp(prop)) continue;
addDefaultProp(prop);
}
}
if (item.type === "class") {
if (item.node.extends) {
const extendsName = trimImport(item.node.extends.getText());
const extendsModel = modelNameToModelMap.get(extendsName);
if (extendsModel) dependencies.add(extendsModel);
}
for (const implemented of item.node.implements) {
const implementsName = trimImport(implemented.getText());
const implementsModel = modelNameToModelMap.get(implementsName);
if (implementsModel) dependencies.add(implementsModel);
}
for (const prop of [
...item.node.properties,
...item.node.methods,
...item.node.declaration.getGetAccessors(),
...item.node.declaration.getSetAccessors(),
]) {
if (addFunctionProp(prop)) continue;
if (addArrayProp(prop)) continue;
if (addGenericProp(prop)) continue;
addDefaultProp(prop);
}
}
dependencyMap.set(item.name, dependencies);
}
// third pass: link dependencies
for (const [name, dependencies] of dependencyMap.entries()) {
const model = modelNameToModelMap.get(name);
if (!model) continue;
for (const dependency of dependencies) {
model.dependencies.push(dependency);
dependency.dependants.push(model);
}
}
return models;
} | // eslint-disable-next-line sonarjs/cognitive-complexity | https://github.com/3rd/tsdiagram/blob/7a7511ccae77b7287c7bec13ced791052da7aec5/src/lib/parser/ModelParser.ts#L91-L514 | 7a7511ccae77b7287c7bec13ced791052da7aec5 |
tsdiagram | github_2023 | 3rd | typescript | addFunctionProp | const addFunctionProp = (prop: Prop, type?: Type) => {
const propName = sanitizePropertyName(prop.getName());
const propType = type ?? prop.getType();
const callSignatures = propType.getCallSignatures();
if (callSignatures.length === 1) {
const callSignature = callSignatures[0];
const functionArguments: { name: string; type: Model | string }[] = [];
for (const parameter of callSignature.getParameters()) {
const parameterName = sanitizePropertyName(parameter.getName());
const parameterTypeName = trimImport(parameter.getTypeAtLocation(prop).getText());
const parameterTypeModel = modelNameToModelMap.get(parameterTypeName);
if (parameterTypeModel) dependencies.add(parameterTypeModel);
functionArguments.push({
name: parameterName,
type: parameterTypeModel ?? parameterTypeName,
});
}
const returnType = callSignature.getReturnType();
const isArray = returnType.isArray();
const returnTypeName = isArray
? trimImport(returnType.getArrayElementType()?.getText() ?? "")
: trimImport(returnType.getText());
const returnTypeModel = modelNameToModelMap.get(returnTypeName);
if (returnTypeModel) dependencies.add(returnTypeModel);
let optional = false;
if (prop.isKind?.(ts.SyntaxKind.PropertySignature)) {
optional = prop.hasQuestionToken();
}
model.schema.push({
name: propName,
type: "function",
arguments: functionArguments,
returnType: isArray ? [returnTypeModel ?? returnTypeName] : returnTypeModel ?? returnTypeName,
optional,
});
return true;
}
return false;
}; | // helpers | https://github.com/3rd/tsdiagram/blob/7a7511ccae77b7287c7bec13ced791052da7aec5/src/lib/parser/ModelParser.ts#L239-L284 | 7a7511ccae77b7287c7bec13ced791052da7aec5 |
tsdiagram | github_2023 | 3rd | typescript | addDefaultProp | const addDefaultProp = (prop: Prop, type?: Type) => {
const propName = sanitizePropertyName(prop.getName());
const propType = type ?? prop.getType();
let typeName = trimImport(propType.getText());
const symbolDeclaration = prop.getSymbol?.()?.getDeclarations()?.[0];
if (symbolDeclaration?.isKind(ts.SyntaxKind.PropertySignature)) {
const declarationName = symbolDeclaration.getTypeNode()?.getText();
if (declarationName) typeName = trimImport(declarationName);
}
const typeModel = modelNameToModelMap.get(typeName);
if (typeModel) dependencies.add(typeModel);
let optional = false;
if (
prop.isKind?.(ts.SyntaxKind.PropertySignature) ||
prop.isKind?.(ts.SyntaxKind.PropertyDeclaration)
) {
optional = prop.hasQuestionToken();
}
model.schema.push({
name: propName,
type: typeModel ?? typeName,
optional,
});
}; | // FIXME: type these functions, prop is Symbol when Type is provided | https://github.com/3rd/tsdiagram/blob/7a7511ccae77b7287c7bec13ced791052da7aec5/src/lib/parser/ModelParser.ts#L366-L393 | 7a7511ccae77b7287c7bec13ced791052da7aec5 |
obsidian-local-gpt | github_2023 | pfrankov | typescript | Logger.separator | separator(message: string = "") {
if (this.isDevMode) {
const lineLength = 20;
const line = "━".repeat(lineLength);
const paddedMessage = message ? ` ${message} ` : "";
const leftPadding = Math.floor(
(lineLength - paddedMessage.length) / 2,
);
const rightPadding =
lineLength - paddedMessage.length - leftPadding;
const separatorLine = message
? line.slice(0, leftPadding) +
paddedMessage +
line.slice(lineLength - rightPadding)
: line;
console.log(
"\n%c" + separatorLine,
"color: #FF4500; font-weight: bold; font-size: 1.2em;",
);
}
} | // Добавляем новый метод для создания разделителя | https://github.com/pfrankov/obsidian-local-gpt/blob/d1a80cc8b12ee7141c14a2234b81efa5ed795914/src/logger.ts#L160-L182 | d1a80cc8b12ee7141c14a2234b81efa5ed795914 |
omnichain | github_2023 | zenoverflow | typescript | isGraphActive | const isGraphActive = (id: string): boolean => {
return executorStorage.get()?.graphId === id;
}; | // Utils | https://github.com/zenoverflow/omnichain/blob/7a0552cd8e0839f28596c703361dc4570a2b994f/server/executor.ts#L46-L48 | 7a0552cd8e0839f28596c703361dc4570a2b994f |
omnichain | github_2023 | zenoverflow | typescript | _buildCustomNodeRegistry | const _buildCustomNodeRegistry = (
registry: [string, string][]
): Record<string, CustomNode> => {
try {
const internalNodes = Object.keys(NODE_MAKERS);
const customNodeRegistry: Record<string, any> = {};
for (const [name, rawJS] of registry) {
try {
const customNodeObj = eval(rawJS) as
| CustomNode
| null
| undefined;
if (!customNodeObj) {
console.error(
`Custom node eval failed for ${name}. Skipping.`
);
continue;
}
if (
internalNodes.includes(
customNodeObj.config.baseConfig.nodeName
)
) {
const n = customNodeObj.config.baseConfig.nodeName;
console.error(
`${n} already exists. Cannot add to custom nodes.`
);
continue;
}
customNodeRegistry[customNodeObj.config.baseConfig.nodeName] =
customNodeObj;
} catch (error) {
console.error(error);
console.error(`Custom node eval failed for ${name}. Skipping.`);
}
}
return customNodeRegistry;
} catch (error) {
console.error(error);
return {};
}
}; | /**
* Build a custom node registry from a list of [filename, rawJS].
* Can be used from the frontend or backend.
*
* @param registry list of [filename, rawJS]
* @returns custom node registry
*/ | https://github.com/zenoverflow/omnichain/blob/7a0552cd8e0839f28596c703361dc4570a2b994f/server/utils.ts#L22-L68 | 7a0552cd8e0839f28596c703361dc4570a2b994f |
omnichain | github_2023 | zenoverflow | typescript | handleClick | const handleClick = (e: any) => {
e.preventDefault();
if (e.button === 1) {
// Editing disabled during execution
const executorState = executorStorage.get();
if (executorState) return;
const editorState = editorStateStorage.get();
if (!editorState) return;
void editorState.editor.removeConnection(props.data.id);
}
}; | // Remove connection on middle-click | https://github.com/zenoverflow/omnichain/blob/7a0552cd8e0839f28596c703361dc4570a2b994f/src/ui/_Rete/CustomConnection.tsx#L114-L126 | 7a0552cd8e0839f28596c703361dc4570a2b994f |
omnichain | github_2023 | zenoverflow | typescript | findNextControlFlowNode | const findNextControlFlowNode = (
currentControl: string,
trigger: string
) => {
const connection = context
.getGraph()
.connections.find(
(c) =>
c.source === currentControl &&
c.sourceOutput === trigger
);
if (!connection || !connection.target || !connection.targetInput) {
return null;
}
return {
nextControl: connection.target,
nextTrigger: connection.targetInput,
};
}; | // Utility function to find the next control-flow node via connections | https://github.com/zenoverflow/omnichain/blob/7a0552cd8e0839f28596c703361dc4570a2b994f/src/util/EngineUtils.ts#L163-L183 | 7a0552cd8e0839f28596c703361dc4570a2b994f |
t3-app-template | github_2023 | gaofubin | typescript | createInnerTRPCContext | const createInnerTRPCContext = (opts: CreateContextOptions) => {
return {
session: opts.session,
prisma,
};
}; | /**
* This helper generates the "internals" for a tRPC context. If you need to use it, you can export
* it from here.
*
* Examples of things you may need it for:
* - testing, so we don't have to mock Next.js' req/res
* - tRPC's `createSSGHelpers`, where we don't have req/res
*
* @see https://create.t3.gg/en/usage/trpc#-serverapitrpcts
*/ | https://github.com/gaofubin/t3-app-template/blob/db31bd3c03b7eb0a099be07c261d856f3b6d4110/src/server/api/trpc.ts#L37-L42 | db31bd3c03b7eb0a099be07c261d856f3b6d4110 |
snapp | github_2023 | urania-dev | typescript | run_init_functions | const run_init_functions = async () => {
database.ping()
const settings = getServerSideSettings();
const savedInDbMFA = await database.settings.get(ENABLED_MFA);
const savedInDbTagsAsPrefix = await database.settings.get(TAGS_AS_PREFIX);
settings.set(
ENABLED_MFA,
savedInDbMFA !== null
? database.settings.parse(savedInDbMFA, true)
: env.ENABLED_MFA?.toString() === "true",
);
settings.set(
TAGS_AS_PREFIX,
savedInDbTagsAsPrefix !== null
? database.settings.parse(savedInDbTagsAsPrefix, true)
: env.TAGS_AS_PREFIX?.toString() === "true",
);
const is_api_limited = database.settings.parse(
await database.settings.get(ENABLE_LIMITS),
true,
);
const rpd = is_api_limited
? parseInt(
(await database.settings.get(MAX_REQUESTS_PER_DAY))?.value || "0",
)
: 0;
const rpm = is_api_limited
? parseInt(
(await database.settings.get(MAX_REQUESTS_PER_MINUTE))?.value || "5",
)
: 0;
if (is_api_limited) {
RPD.configure(24 * 60 * 60 * 1000, rpd);
RPM.configure(60 * 1000, rpm);
}
}; | // INIT DB | https://github.com/urania-dev/snapp/blob/fe2a49f5a32001c44e590e42db20612fa89baa60/src/hooks.server.ts#L21-L57 | fe2a49f5a32001c44e590e42db20612fa89baa60 |
wingman-ai | github_2023 | RussellCanfield | typescript | CodeSuggestionProvider.constructor | constructor(
private readonly _aiProvider: AIProvider | AIStreamProvider,
private readonly _settings: Settings
) {
//this.cacheManager = new CacheManager();
} | //private cacheManager: CacheManager; | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/providers/codeSuggestionProvider.ts#L31-L36 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | addNoneAttribute | const addNoneAttribute = (match: string) => {
if (match.includes("nonce=")) {
// If none attribute already exists, return the original match
return match;
} else {
// Add none attribute before the closing angle bracket
return match.replace(/>$/, ` nonce="${noneValue}">`);
}
}; | // Function to add the none attribute | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/providers/utilities.ts#L174-L182 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | CodeParser.mergeCodeNodeSummariesIntoParent | mergeCodeNodeSummariesIntoParent(
parentNodeLocation: Location,
parentCodeBlock: string,
relatedNodeEdgeIds: string[],
skeletonNodes: SkeletonizedCodeGraphNode[]
) {
let codeBlock = parentCodeBlock;
for (const childNodeId of relatedNodeEdgeIds) {
const childNode = skeletonNodes.find((n) => n.id === childNodeId);
if (!childNode) {
continue;
}
codeBlock = this.replaceLineRange(
codeBlock,
childNode.location.range.start.line -
parentNodeLocation.range.start.line,
childNode.location.range.end.line -
parentNodeLocation.range.start.line,
[childNode.skeleton]
);
}
return codeBlock;
} | // This is not perfect, but it's a good start | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/server/files/parser.ts#L118-L143 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | getCachedDocument | const getCachedDocument = async (
uri: string
): Promise<TextDocument | undefined> => {
if (!documentCache.has(uri)) {
const doc = await getTextDocumentFromUri(uri);
if (doc) {
documentCache.set(uri, doc);
}
}
return documentCache.get(uri)!;
}; | // Helper function to get text document, with caching | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/server/files/parser.ts#L171-L181 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | DiffGenerator.getBaseBranch | public async getBaseBranch(): Promise<string> {
const upstream = await this.executeGitCommand(
"git rev-parse --abbrev-ref @{upstream}"
);
return upstream.split("/")[1] || "main";
} | /**
* Gets the base branch name (usually main or master)
* @returns The base branch name
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/utils/diffGenerator.ts#L29-L34 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | DiffGenerator.getOriginalContent | public async getOriginalContent(filePath: string): Promise<string> {
try {
// Get merge base commit
const mergeBase = await this.executeGitCommand(
`git merge-base HEAD ${await this.getBaseBranch()}`
);
// Get file content at merge base
return await this.executeGitCommand(
`git show ${mergeBase.trim()}:${filePath}`
);
} catch (error) {
console.error("Failed to get original content:", error);
return "";
}
} | /**
* Gets the content of a file from the base branch
* @param filePath The path to the file
* @returns The file content from the base branch
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/utils/diffGenerator.ts#L41-L56 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | DiffGenerator.executeGitCommand | private async executeGitCommand(command: string): Promise<string> {
try {
const { stdout } = await execAsync(command, {
cwd: this.cwd,
});
return stdout.trim();
} catch (error) {
if (error instanceof Error) {
throw new Error(`Git command failed: ${error.message}`);
}
}
return "";
} | /**
* Executes a git command and returns the output
* @param command The git command to execute
* @returns The command output
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/utils/diffGenerator.ts#L63-L76 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | DiffGenerator.getCurrentBranch | public async getCurrentBranch(): Promise<string> {
return this.executeGitCommand("git rev-parse --abbrev-ref HEAD");
} | /**
* Gets the current git branch name
* @returns The current branch name
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/utils/diffGenerator.ts#L82-L84 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | DiffGenerator.showDiffForFile | public async showDiffForFile(filePath: string): Promise<string> {
return this.executeGitCommand(`git diff HEAD -- "${filePath}"`);
} | /**
* Shows diff for a specific file
* @param filePath The path of the file to show diff for
* @returns The git diff output for the specified file
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/utils/diffGenerator.ts#L356-L358 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | DiffGenerator.getChangedFiles | public async getChangedFiles(): Promise<string[]> {
const output = await this.executeGitCommand(
"git diff HEAD --name-only"
);
return output.split("\n").filter((file) => file.length > 0);
} | /**
* Gets a list of changed files in the current branch
* @returns Array of changed file paths
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/utils/diffGenerator.ts#L364-L369 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | GitCommandEngine.executeCommand | protected async executeCommand(command: string): Promise<string> {
try {
const { stdout } = await execAsync(command, {
cwd: this.cwd,
});
return stdout.trim();
} catch (error) {
if (error instanceof Error) {
throw new Error(`Git command failed: ${error.message}`);
}
}
return "";
} | /**
* Executes a git command and returns the output
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/src/utils/gitCommandEngine.ts#L19-L31 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | VSCodeAPIWrapper.postMessage | public postMessage(message: unknown) {
if (this.vsCodeApi) {
this.vsCodeApi.postMessage(message);
} else {
console.log(message);
}
} | /**
* Post a message (i.e. send arbitrary data) to the owner of the webview.
*
* @remarks When running webview code inside a web browser, postMessage will instead
* log the given message to the console.
*
* @param message Abitrary data (must be JSON serializable) to send to the extension context.
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Chat/utilities/vscode.ts#L31-L37 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | VSCodeAPIWrapper.getState | public getState(): unknown | undefined {
if (this.vsCodeApi) {
return this.vsCodeApi.getState();
} else {
const state = localStorage.getItem("vscodeState");
return state ? JSON.parse(state) : undefined;
}
} | /**
* Get the persistent state stored for this webview.
*
* @remarks When running webview source code inside a web browser, getState will retrieve state
* from local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
*
* @return The current state or `undefined` if no state has been set.
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Chat/utilities/vscode.ts#L47-L54 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | VSCodeAPIWrapper.setState | public setState<T extends unknown | undefined>(newState: T): T {
if (this.vsCodeApi) {
return this.vsCodeApi.setState(newState);
} else {
localStorage.setItem("vscodeState", JSON.stringify(newState));
return newState;
}
} | /**
* Set the persistent state stored for this webview.
*
* @remarks When running webview source code inside a web browser, setState will set the given
* state using local storage (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
*
* @param newState New persisted state. This must be a JSON serializable object. Can be retrieved
* using {@link getState}.
*
* @return The new state.
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Chat/utilities/vscode.ts#L67-L74 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
wingman-ai | github_2023 | RussellCanfield | typescript | constructLines | const constructLines = (value: string): string[] => {
if (value === "") return [];
const lines = value.replace(/\n$/, "").split("\n");
return lines;
}; | /**
* Splits diff text by new line and computes final list of diff lines based on
* conditions.
*
* @param value Diff text from the js diff module.
*/ | https://github.com/RussellCanfield/wingman-ai/blob/7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6/views-ui/src/Common/DiffView/compute-lines.ts#L60-L66 | 7c8c4c83499eaaf9c403a5613dbeb41ffb536ff6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.