@prisma/extension-optimize 0.9.0-dev.3 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +7 -3
- package/dist/index.js +3 -3
- package/package.json +11 -11
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import * as _prisma_client_extension from '@prisma/client/extension';
|
|
2
2
|
import * as _prisma_client_runtime_library from '@prisma/client/runtime/library';
|
|
3
3
|
|
|
4
|
-
declare const PROD_INGESTION_URL = "https://optimize-ingestion
|
|
5
|
-
declare const PROD_DASHBOARD_URL = "https://optimize
|
|
4
|
+
declare const PROD_INGESTION_URL = "https://optimize-ingestion.datacdn.workers.dev/";
|
|
5
|
+
declare const PROD_DASHBOARD_URL = "https://optimize.prisma.io";
|
|
6
6
|
type OptimizeOptions = {
|
|
7
7
|
/**
|
|
8
8
|
* Whether to enable Prisma Optimize. Defaults to `true`.
|
|
@@ -16,6 +16,10 @@ type OptimizeOptions = {
|
|
|
16
16
|
* The URL of the dashboard of Prisma Optimize
|
|
17
17
|
*/
|
|
18
18
|
dashboardUrl?: string;
|
|
19
|
+
/**
|
|
20
|
+
* The token to use to authenticate Prisma Optimize
|
|
21
|
+
*/
|
|
22
|
+
token?: string;
|
|
19
23
|
/**
|
|
20
24
|
* In the past, this used to configure whether to use tracing or not.
|
|
21
25
|
* This is now a no-op and will be completely removed in a future version.
|
|
@@ -33,6 +37,6 @@ type OptimizeOptions = {
|
|
|
33
37
|
*/
|
|
34
38
|
showToast?: boolean;
|
|
35
39
|
};
|
|
36
|
-
declare function withOptimize({ enable, ingestionUrl, dashboardUrl, minSendInterval, showToast, }?: OptimizeOptions): (client: any) => _prisma_client_extension.PrismaClientExtends<_prisma_client_runtime_library.InternalArgs<{}, {}, {}, {}> & _prisma_client_runtime_library.DefaultArgs>;
|
|
40
|
+
declare function withOptimize({ enable, ingestionUrl, dashboardUrl, minSendInterval, showToast, token: givenToken, }?: OptimizeOptions): (client: any) => _prisma_client_extension.PrismaClientExtends<_prisma_client_runtime_library.InternalArgs<{}, {}, {}, {}> & _prisma_client_runtime_library.DefaultArgs>;
|
|
37
41
|
|
|
38
42
|
export { type OptimizeOptions, PROD_DASHBOARD_URL, PROD_INGESTION_URL, withOptimize };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`:(R("sql attribute is not a string: %o",o),n)},"")}toIngestRequestItem(e){if(this.duration===void 0)throw new Error("`duration` is `undefined`, this should not happen");return{ts:this.timestamp,model:this.model??null,operation:this.operation,args:this.args,latency:this.duration,connect:this.connect??!1,sql:this.statementSpansToString(),error:this.error??null,hash:e}}},g=class{#e=new Map;#o=Promise.resolve();#t=new Map;#n=new Map;#a;#p;#r=new Set;#m=Promise.resolve();#i=!1;#
|
|
1
|
+
"use strict";var ge=Object.create;var f=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var we=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty;var be=(t,e)=>{for(var n in e)f(t,n,{get:e[n],enumerable:!0})},v=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ye(e))!Ce.call(t,o)&&o!==n&&f(t,o,{get:()=>e[o],enumerable:!(r=Se(e,o))||r.enumerable});return t};var a=(t,e,n)=>(n=t!=null?ge(we(t)):{},v(e||!t||!t.__esModule?f(n,"default",{value:t,enumerable:!0}):n,t)),Re=t=>v(f({},"__esModule",{value:!0}),t);var Le={};be(Le,{PROD_DASHBOARD_URL:()=>le,PROD_INGESTION_URL:()=>ce,withOptimize:()=>Fe});module.exports=Re(Le);var ie=require("@opentelemetry/api"),se=require("@prisma/client/extension"),ae=a(require("@prisma/debug")),pe=a(require("kleur")),me=a(require("readline-sync"));function xe(t,e){let n;return async function(r,o,p){let c=new URL(r,t),s=new Headers({"Content-Type":"application/json",Authorization:`Bearer ${e}`});n&&s.set("prisma-optimize-jwt",n);let i=await fetch(c,{method:o,headers:s,body:JSON.stringify(p)});if(!i.ok){let l=await i.text().catch(()=>"<unreadable>");throw console.error(`[optimize] HTTP ${i.status} ${i.statusText}: ${l}`),i.status===401&&(console.error("[optimize] Try logging out, run `npx prisma@optimize platform auth logout --early-access --optimize`"),console.error("[optimize] And log in again, run `npx prisma@optimize platform auth login --early-access --optimize`")),new Error(`Optimize error ${i.status} ${i.statusText}: ${l}`)}let m=i.headers.get("prisma-optimize-jwt");return m&&(n=m),i}}function T(t,e){let n=xe(t,e);return{request:n,post:(r,o)=>n(r,"POST",o)}}async function q(t,e){return(await t.post("/schema",{schema:e})).text()}var E=a(require("fs")),k=a(require("path")),A=require("@prisma/debug"),z=a(require("xdg-app-paths")),Ie=(0,A.Debug)("prisma:extension:optimize"),Pe=new z.default("prisma-platform-cli").config(),ve=k.default.join(Pe,"auth.json");function Te(t){if(typeof t!="object"||t===null)throw new Error("Invalid credentials");if(typeof t.token!="string")throw new Error("Invalid credentials");return t}function w(){try{let t=E.default.readFileSync(ve,"utf-8");return Te(JSON.parse(t)).token}catch(t){return Ie(t),null}}var O=require("child_process");function F(){let t=(0,O.spawnSync)("npx",["--yes","prisma@optimize","platform","auth","login","--early-access","--optimize"],{stdio:"inherit",shell:!0});if(t.error)throw t.error}var u=a(require("fs")),L=a(require("path")),M=require("stream"),_=require("stream/promises"),$=a(require("kleur")),U=require("node-notifier"),j=a(require("xdg-app-paths")),qe="https://avatars.githubusercontent.com/u/17219288?s=96",{bold:Ee,underline:ke}=$.default;async function N(t){let e=new j.default("prisma-optimize").config();u.default.mkdirSync(e,{recursive:!0});let n=L.default.resolve(e,"avatar.png");if(!u.default.existsSync(n)){let i=await fetch(qe);if(i.ok&&i.body!=null){let m=u.default.createWriteStream(n,{flags:"wx"});await(0,_.finished)(M.Readable.fromWeb(i.body).pipe(m))}}let r="See your Optimize dashboard at:",o=r.length,p=`${ke(Ee(t))}`,c=t.length,s=Math.max(o,c)+2;console.log("\u250C"+"\u2500".repeat(s)+"\u2510"),console.log("\u2502 "+r+" ".repeat(s-o-2)+" \u2502"),console.log("\u2502 "+p+" ".repeat(s-c-2)+" \u2502"),console.log("\u2514"+"\u2500".repeat(s)+"\u2518"),(0,U.notify)({timeout:10,open:t,subtitle:"Your dashboard is ready! \u{1F680} ",message:"Click to open",title:"Prisma Optimize",icon:u.default.existsSync(n)?n:void 0,contentImage:u.default.existsSync(n)?n:void 0})}var Q=require("@opentelemetry/api"),V=require("@opentelemetry/context-async-hooks"),W=require("@opentelemetry/instrumentation"),Y=require("@opentelemetry/resources"),G=require("@opentelemetry/sdk-trace-base"),S=require("@opentelemetry/semantic-conventions"),X=require("@prisma/instrumentation");var J=a(require("@prisma/debug"));async function D(t,e){await t.post("/ingest",e)}function C(t,...e){setTimeout(()=>{t(...e)},0)}function h(t){return t[0]*1e3+t[1]/1e6}var R=(0,J.default)("prisma:extension:optimize"),b="0000000000000000",B=(o=>(o.ClientOperation="prisma:client:operation",o.ClientConnect="prisma:client:connect",o.Engine="prisma:engine",o.EngineQuery="prisma:engine:db_query",o))(B||{}),x=class{spanId;timestamp;model;operation;args;statementSpans;duration;connect;error;completionFlags={clientSpanClosed:!1,engineSpanClosed:!1};constructor(e){this.spanId=e.spanId,this.timestamp=e.timestamp,this.model=e.model,this.operation=e.operation,this.args=e.args,this.statementSpans=[]}isCompleted(){return this.completionFlags.clientSpanClosed&&this.completionFlags.engineSpanClosed}statementSpansToString(){return this.statementSpans.sort((n,r)=>{let o=h(n.startTime),p=h(r.startTime);return o-p}).reduce((n,r)=>{let o=r.attributes["db.statement"];return typeof o=="string"?`${n}${o}
|
|
2
|
+
`:(R("sql attribute is not a string: %o",o),n)},"")}toIngestRequestItem(e){if(this.duration===void 0)throw new Error("`duration` is `undefined`, this should not happen");return{ts:this.timestamp,model:this.model??null,operation:this.operation,args:this.args,latency:this.duration,connect:this.connect??!1,sql:this.statementSpansToString(),error:this.error??null,hash:e}}},g=class{#e=new Map;#o=Promise.resolve();#t=new Map;#n=new Map;#a;#p;#r=new Set;#m=Promise.resolve();#i=!1;#c;setSchemaHash=()=>{};constructor(e,n){this.#a=e,this.#p=n,this.#c=new Promise(r=>{this.setSchemaHash=r})}createRequest(e){let n=new x(e);this.#e.set(e.spanId,n)}setRequestError(e,n){let r=this.#e.get(e);if(!r)throw new Error(`Unknown request ${e}`);r.error=n}#u(e){for(let n=e;n!==b;n=this.#t.get(n)){if(n===void 0)return{type:"UndeliveredSpanInTree"};let r=this.#e.get(n);if(r)return{type:"Ok",request:r}}return{type:"NotInRequestTree"}}onStart(e,n){if(!H(e))return;let r=e.spanContext().spanId;if(!e.parentSpanId){this.#t.set(r,b);return}if(this.#t.set(r,e.parentSpanId),e.parentSpanId===b)return;let o=this.#n.get(e.parentSpanId);o?o.add(r):this.#n.set(e.parentSpanId,new Set([r]))}onEnd(e){H(e)&&this.#l(e)}async forceFlush(){await this.#o,await this.#d()}async shutdown(){await this.forceFlush()}#l(e){let n=e.spanContext().spanId,r,o=this.#u(n);switch(o.type){case"Ok":r=o.request;break;case"UndeliveredSpanInTree":this.#h(e);break;case"NotInRequestTree":this.#s(n);break}if(r){switch(e.name){case"prisma:client:connect":{r.connect=h(e.duration);break}case"prisma:engine":{r.completionFlags.engineSpanClosed=!0;break}case"prisma:engine:db_query":{r.statementSpans.push(e);break}case"prisma:client:operation":{r.duration=h(e.duration),r.completionFlags.clientSpanClosed=!0,R("latency otel: %d",r.duration);break}}r.isCompleted()&&this.#f(r)}}#h(e){this.#o=Promise.all([this.#o,new Promise(C).then(()=>this.#l(e))])}#s(e){this.#t.delete(e);let n=this.#n.get(e);if(this.#n.delete(e),n)for(let r of n)this.#s(r)}#f(e){C(()=>{this.#e.delete(e.spanId),this.#s(e.spanId),this.#r.add(e),this.#g()})}async#g(){await this.#m,!this.#i&&(this.#i=!0,setTimeout(()=>{this.#m=this.#d().finally(()=>{this.#i=!1})},this.#p))}async#d(){if(this.#r.size===0)return;let e=await this.#c,n=[...this.#r].map(r=>r.toIngestRequestItem(e));this.#r.clear(),R("sending batch of %d requests",n.length);try{await D(this.#a,n)}catch(r){console.error(r.message??r)}}};function H(t){return Object.values(B).includes(t.name)}function Z(t,e){let n=new V.AsyncHooksContextManager().enable();Q.context.setGlobalContextManager(n);let r=new G.BasicTracerProvider({resource:new Y.Resource({[S.SEMRESATTRS_SERVICE_NAME]:"extension-optimize",[S.SEMRESATTRS_SERVICE_VERSION]:"0.0.0"})}),o=new g(t,e);return r.addSpanProcessor(o),(0,W.registerInstrumentations)({tracerProvider:r,instrumentations:[new X.PrismaInstrumentation]}),r.register(),o}function K(t){return t._previewFeatures?.includes("tracing")}function ee(t){return t._engineConfig.inlineSchema}function te(t){if(t instanceof Error)return t.stack??t.message;switch(typeof t){case"undefined":return"undefined";case"object":{let e;return t!==null&&typeof t.toString=="function"&&(e=t.toString()),typeof e=="string"&&e!=="[object Object]"?e:JSON.stringify(t)}default:return String(t)}}var ne=require("@prisma/client/extension"),re=ne.Prisma.defineExtension(t=>t.$extends({}));var{bold:Ae,dim:ze}=pe.default,ce="https://optimize-ingestion.datacdn.workers.dev/",le="https://optimize.prisma.io",Oe=(0,ae.default)("prisma:extension:optimize"),oe=`You need to login to Prisma Data Platform using the CLI to use Prisma Optimize:
|
|
3
3
|
|
|
4
|
-
${
|
|
4
|
+
${ze("$")} ${Ae("npx prisma@optimize platform auth login --early-access --optimize")}`;function Fe({enable:t=!0,ingestionUrl:e=ce,dashboardUrl:n=le,minSendInterval:r=50,showToast:o=!0,token:p}={}){if(!t)return re;let c=new URL(e),s=p??w();if(!s)if(process.stdin.isTTY){if(console.error(oe),me.default.keyInYN("Run this command now?")&&(F(),s=w()),!s)throw new Error("Please login to Prisma Data Platform to use Prisma Optimize: either via the CLI, or by providing `token` as an option to `withOptimize()`")}else throw new Error(oe);return o&&N(n).then().catch(i=>{console.error("Failed to show toast",i)}),se.Prisma.defineExtension(i=>{let m=T(c,s),l=Z(m,r);if(!K(i))throw new Error('Please enable the "tracing" preview feature and regenerate the client.');let de=ee(i);return q(m,de).then(d=>{Oe("uploaded schema with hash",d),l.setSchemaHash(d)},d=>{console.error(d),console.error("Failed to upload the schema, no data will be sent to Prisma Optimize")}),i.$extends({query:{async $allOperations({query:d,model:ue,operation:he,args:I}){let y=ie.trace.getActiveSpan()?.spanContext().spanId;if(!y)throw new Error("prisma:client:operation span is expected to be entered in the client extension when tracing is enabled");l.createRequest({spanId:y,timestamp:Date.now(),model:ue,operation:he,args:I});try{return await d(I)}catch(P){let fe=te(P);throw l.setRequestError(y,fe),P}}}})})}0&&(module.exports={PROD_DASHBOARD_URL,PROD_INGESTION_URL,withOptimize});
|
package/package.json
CHANGED
|
@@ -1,16 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/extension-optimize",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"sideEffects": false,
|
|
5
5
|
"description": "",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
|
-
"scripts": {
|
|
9
|
-
"typecheck": "tsc --noEmit",
|
|
10
|
-
"build": "tsup src/index.ts --minify --dts --format cjs --out-dir dist",
|
|
11
|
-
"lint": "eslint --fix .",
|
|
12
|
-
"test": "vitest --run"
|
|
13
|
-
},
|
|
14
8
|
"keywords": [],
|
|
15
9
|
"dependencies": {
|
|
16
10
|
"@opentelemetry/api": "1.8.0",
|
|
@@ -31,15 +25,21 @@
|
|
|
31
25
|
"@hono/node-server": "1.9.1",
|
|
32
26
|
"@types/node-notifier": "8.0.5",
|
|
33
27
|
"@types/readline-sync": "1.4.8",
|
|
34
|
-
"common": "workspace:*",
|
|
35
28
|
"hono": "4.4.6",
|
|
36
29
|
"tsup": "8.0.2",
|
|
37
|
-
"vitest": "1.4.0"
|
|
30
|
+
"vitest": "1.4.0",
|
|
31
|
+
"common": "0.0.0"
|
|
38
32
|
},
|
|
39
33
|
"peerDependencies": {
|
|
40
34
|
"@prisma/client": "5.x"
|
|
41
35
|
},
|
|
42
36
|
"files": [
|
|
43
37
|
"dist"
|
|
44
|
-
]
|
|
45
|
-
|
|
38
|
+
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"typecheck": "tsc --noEmit",
|
|
41
|
+
"build": "tsup src/index.ts --minify --dts --format cjs --out-dir dist",
|
|
42
|
+
"lint": "eslint --fix .",
|
|
43
|
+
"test": "vitest --run"
|
|
44
|
+
}
|
|
45
|
+
}
|