@typekcz-nocobase-plugins/plugin-oidc-plus 1.0.2 → 1.0.3

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.
@@ -7,6 +7,4 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- (function(o,n){typeof exports=="object"&&typeof module!="undefined"?n(exports,require("@nocobase/client"),require("@nocobase/plugin-auth/client"),require("react/jsx-runtime"),require("@ant-design/icons"),require("antd"),require("react"),require("react-i18next"),require("react-router-dom"),require("@formily/antd-v5"),require("@formily/react")):typeof define=="function"&&define.amd?define(["exports","@nocobase/client","@nocobase/plugin-auth/client","react/jsx-runtime","@ant-design/icons","antd","react","react-i18next","react-router-dom","@formily/antd-v5","@formily/react"],n):(o=typeof globalThis!="undefined"?globalThis:o||self,n(o["@typekcz-nocobase-plugins/plugin-oidc-plus"]={},o["@nocobase/client"],o["@nocobase/plugin-auth"],o.jsxRuntime,o["@ant-design/icons"],o.antd,o.react,o["react-i18next"],o["react-router-dom"],o["@formily/antd-v5"],o["@formily/react"]))})(this,function(o,n,h,s,v,u,b,I,d,y,U){"use strict";var w=(o,n,h)=>new Promise((s,v)=>{var u=d=>{try{I(h.next(d))}catch(y){v(y)}},b=d=>{try{I(h.throw(d))}catch(y){v(y)}},I=d=>d.done?s(d.value):Promise.resolve(d.value).then(u,b);I((h=h.apply(o,n)).next())});const j="OIDC+",T="tnp_oidc_plus_logout",P="oidc";function c(e){return n.i18n.t(e,{ns:P})}function C(){return I.useTranslation(P)}/*! js-cookie v3.0.5 | MIT */function S(e){for(var a=1;a<arguments.length;a++){var l=arguments[a];for(var m in l)e[m]=l[m]}return e}var q={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function F(e,a){function l(t,x,r){if(typeof document!="undefined"){r=S({},a,r),typeof r.expires=="number"&&(r.expires=new Date(Date.now()+r.expires*864e5)),r.expires&&(r.expires=r.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var p in r)r[p]&&(i+="; "+p,r[p]!==!0&&(i+="="+r[p].split(";")[0]));return document.cookie=t+"="+e.write(x,t)+i}}function m(t){if(!(typeof document=="undefined"||arguments.length&&!t)){for(var x=document.cookie?document.cookie.split("; "):[],r={},i=0;i<x.length;i++){var p=x[i].split("="),f=p.slice(1).join("=");try{var g=decodeURIComponent(p[0]);if(r[g]=e.read(f,g),t===g)break}catch(D){}}return t?r[t]:r}}return Object.create({set:l,get:m,remove:function(t,x){l(t,"",S({},x,{expires:-1}))},withAttributes:function(t){return F(this.converter,S({},this.attributes,t))},withConverter:function(t){return F(S({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(a)},converter:{value:Object.freeze(e)}})}var k=F(q,{path:"/"});const E=({authenticator:e})=>{const{t:a}=C(),l=n.useAPIClient(),m=d.useLocation(),t=new URLSearchParams(m.search),x=t.get("redirect"),r=()=>w(this,null,function*(){var f;const i=yield l.request({method:"post",url:"oidc:getAuthUrl",headers:{"X-Authenticator":e.name},data:{redirect:x}}),p=(f=i==null?void 0:i.data)==null?void 0:f.data;window.location.replace(p)});return b.useEffect(()=>{const i=k.get(T);if(i){const g=new URL(i);g.searchParams.set("post_logout_redirect_uri",window.location.href),console.log(T,{domain:window.location.hostname}),k.remove(T,{domain:window.location.hostname}),window.location.href=g.href}const p=t.get("authenticator"),f=t.get("error");if(p===e.name&&f){u.message.error(a(f));return}}),s.jsx(u.Space,{direction:"vertical",className:n.css`
11
- display: flex;
12
- `,children:s.jsx(u.Button,{shape:"round",block:!0,icon:s.jsx(v.LoginOutlined,{}),onClick:r,children:a(e.title)})})},O={type:"object",properties:{public:{type:"object",properties:{autoSignup:{"x-decorator":"FormItem",type:"boolean",title:'{{t("Sign up automatically when the user does not exist")}}',"x-component":"Checkbox",default:!0}}},oidc:{type:"object",properties:{collapse:{type:"void","x-component":"FormTab",properties:{basic:{type:"void","x-component":"FormTab.TabPane","x-component-props":{tab:c("Basic configuration")},properties:{issuer:{type:"string",title:'{{t("Issuer")}}',"x-component":"Input","x-decorator":"FormItem",required:!0},clientId:{type:"string",title:'{{t("Client ID")}}',"x-component":"Input","x-decorator":"FormItem",required:!0},clientSecret:{type:"string",title:'{{t("Client Secret")}}',"x-component":"Input","x-decorator":"FormItem",required:!0},scope:{type:"string",title:'{{t("scope")}}',"x-component":"Input","x-decorator":"FormItem","x-decorator-props":{tooltip:'{{t("Default: openid profile email")}}'}},idTokenSignedResponseAlg:{type:"string",title:'{{t("id_token signed response algorithm")}}',"x-component":"Select","x-decorator":"FormItem",enum:[{label:"HS256",value:"HS256"},{label:"HS384",value:"HS384"},{label:"HS512",value:"HS512"},{label:"RS256",value:"RS256"},{label:"RS384",value:"RS384"},{label:"RS512",value:"RS512"},{label:"ES256",value:"ES256"},{label:"ES384",value:"ES384"},{label:"ES512",value:"ES512"},{label:"PS256",value:"PS256"},{label:"PS384",value:"PS384"},{label:"PS512",value:"PS512"}]}}},mapping:{type:"void","x-component":"FormTab.TabPane","x-component-props":{tab:c("Field mapping")},properties:{fieldMap:{title:'{{t("Field Map")}}',type:"array","x-decorator":"FormItem","x-component":"ArrayItems",items:{type:"object","x-decorator":"ArrayItems.Item",properties:{space:{type:"void","x-component":"Space",properties:{source:{type:"string","x-decorator":"FormItem","x-component":"Input","x-component-props":{placeholder:'{{t("source")}}'}},target:{type:"string","x-decorator":"FormItem","x-component":"Input","x-component-props":{placeholder:'{{t("target")}}'}},remove:{type:"void","x-decorator":"FormItem","x-component":"ArrayItems.Remove"}}}}},properties:{add:{type:"void",title:"Add","x-component":"ArrayItems.Addition"}}},userBindField:{type:"string",title:'{{t("Use this field to bind the user")}}',"x-component":"Select","x-decorator":"FormItem",default:"email",enum:[{label:c("Email"),value:"email"},{label:c("Username"),value:"username"}],required:!0}}},advanced:{type:"void","x-component":"FormTab.TabPane","x-component-props":{tab:c("Advanced configuration")},properties:{logout:{type:"boolean",title:'{{t("RP-initiated logout")}}',"x-component":"Checkbox","x-decorator":"FormItem","x-decorator-props":{tooltip:'{{t("Performs logout on the issuer (uses end_session_endpoint in the issuer configuration)")}}'}},http:{type:"boolean",title:'{{t("HTTP")}}',"x-component":"Checkbox","x-decorator":"FormItem","x-decorator-props":{tooltip:'{{t("Check if NocoBase is running on HTTP protocol")}}'}},port:{type:"number",title:'{{t("Port")}}',"x-component":"InputNumber","x-decorator":"FormItem","x-decorator-props":{tooltip:'{{t("The port number of the NocoBase service if it is not 80 or 443")}}'},"x-component-props":{style:{width:"15%",minWidth:"100px"}}},stateToken:{type:"string",title:'{{t("State token")}}',"x-component":"Input","x-decorator":"FormItem",description:c("The state token helps prevent CSRF attacks. It's recommended to leave it blank for automatic random generation.")},exchangeBodyKeys:{type:"array",title:'{{t("Pass parameters in the authorization code grant exchange")}}',"x-decorator":"FormItem","x-component":"ArrayItems",default:[{paramName:"",optionsKey:"clientId"},{paramName:"",optionsKey:"clientSecret"}],items:{type:"object","x-decorator":"ArrayItems.Item",properties:{space:{type:"void","x-component":"Space",properties:{enabled:{type:"boolean","x-decorator":"FormItem","x-component":"Checkbox"},optionsKey:{type:"string","x-decorator":"FormItem","x-decorator-props":{style:{width:"100px"}},"x-component":"Select","x-read-pretty":!0,enum:[{label:c("Client ID"),value:"clientId"},{label:c("Client Secret"),value:"clientSecret"}]},paramName:{type:"string","x-decorator":"FormItem","x-component":"Input","x-component-props":{placeholder:'{{t("Parameter name")}}'}}}}}}},userInfoMethod:{type:"string",title:'{{t("Method to call the user info endpoint")}}',"x- decorator":"FormItem","x-component":"Radio.Group",default:"GET",enum:[{label:"GET",value:"GET"},{label:"POST",value:"POST"}],"x-reactions":[{dependencies:[".accessTokenVia"],when:'{{$deps[0] === "query"}}',fulfill:{state:{value:"GET"}}},{dependencies:[".accessTokenVia"],when:'{{$deps[0] === "body"}}',fulfill:{state:{value:"POST"}}}]},accessTokenVia:{type:"string",title:'{{t("Where to put the access token when calling the user info endpoint")}}',"x- decorator":"FormItem","x-component":"Radio.Group",default:"header",enum:[{label:c("Header"),value:"header"},{label:c("Body (Use with POST method)"),value:"body"},{label:c("Query parameters (Use with GET method)"),value:"query"}]}}}}}}},usage:{type:"void","x-component":"Usage"}}},R=U.observer(()=>{const{t:e}=C(),a=n.useApp(),l=b.useMemo(()=>a.getApiUrl("oidc:redirect"),[a]),m=t=>{navigator.clipboard.writeText(t),u.message.success(e("Copied"))};return s.jsx(u.Card,{title:e("Usage"),type:"inner",children:s.jsx(n.FormItem,{label:e("Redirect URL"),children:s.jsx(n.Input,{value:l,disabled:!0,addonBefore:s.jsx(v.CopyOutlined,{onClick:()=>m(l)})})})})},{displayName:"Usage"}),B=()=>{const{t:e}=C();return s.jsx(n.SchemaComponent,{scope:{t:e},components:{Usage:R,ArrayItems:y.ArrayItems,Space:u.Space,FormTab:y.FormTab},schema:O})};class A extends n.Plugin{load(){return w(this,null,function*(){this.app.pm.get(h).registerType(j,{components:{SignInButton:E,AdminSettingsForm:B}})})}}o.PluginOIDCClient=A,o.default=A,Object.defineProperties(o,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
10
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react-i18next"),require("@nocobase/plugin-auth/client"),require("@nocobase/client"),require("antd"),require("@ant-design/icons"),require("@formily/react"),require("react-router-dom"),require("react"),require("@formily/antd-v5")):"function"==typeof define&&define.amd?define("@typekcz-nocobase-plugins/plugin-oidc-plus",["react-i18next","@nocobase/plugin-auth/client","@nocobase/client","antd","@ant-design/icons","@formily/react","react-router-dom","react","@formily/antd-v5"],t):"object"==typeof exports?exports["@typekcz-nocobase-plugins/plugin-oidc-plus"]=t(require("react-i18next"),require("@nocobase/plugin-auth/client"),require("@nocobase/client"),require("antd"),require("@ant-design/icons"),require("@formily/react"),require("react-router-dom"),require("react"),require("@formily/antd-v5")):e["@typekcz-nocobase-plugins/plugin-oidc-plus"]=t(e["react-i18next"],e["@nocobase/plugin-auth/client"],e["@nocobase/client"],e.antd,e["@ant-design/icons"],e["@formily/react"],e["react-router-dom"],e.react,e["@formily/antd-v5"])}(self,function(e,t,r,o,n,i,a,c,u){return function(){"use strict";var l={482:function(e){e.exports=n},632:function(e){e.exports=u},505:function(e){e.exports=i},772:function(e){e.exports=r},689:function(e){e.exports=t},721:function(e){e.exports=o},156:function(e){e.exports=c},238:function(t){t.exports=e},128:function(e){e.exports=a}},p={};function s(e){var t=p[e];if(void 0!==t)return t.exports;var r=p[e]={exports:{}};return l[e](r,r.exports,s),r.exports}s.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return s.d(t,{a:t}),t},s.d=function(e,t){for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},s.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},s.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var d={};s.r(d),s.d(d,{PluginOIDCClient:function(){return N},default:function(){return L}});var f=s("772"),m=s("689"),y=s.n(m),b="tnp_oidc_plus_logout",v=s("482"),h=s("721"),x=s("156"),g=s.n(x),S=s("238"),I="oidc";function w(e){return f.i18n.t(e,{ns:I})}function T(){return(0,S.useTranslation)(I)}var P=s("128");function F(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)e[o]=r[o]}return e}var k=function e(t,r){function o(e,o,n){if("undefined"!=typeof document){"number"==typeof(n=F({},r,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var a in n){if(!n[a])continue;if(i+="; "+a,!0!==n[a])i+="="+n[a].split(";")[0]}return document.cookie=e+"="+t.write(o,e)+i}}return Object.create({set:o,get:function(e){if("undefined"!=typeof document&&(!arguments.length||!!e)){for(var r=document.cookie?document.cookie.split("; "):[],o={},n=0;n<r.length;n++){var i=r[n].split("="),a=i.slice(1).join("=");try{var c=decodeURIComponent(i[0]);if(o[c]=t.read(a,c),e===c)break}catch(e){}}return e?o[e]:o}},remove:function(e,t){o(e,"",F({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,F({},this.attributes,t))},withConverter:function(t){return e(F({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(r)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function C(e,t,r,o,n,i,a){try{var c=e[i](a),u=c.value}catch(e){r(e);return}c.done?t(u):Promise.resolve(u).then(o,n)}function O(){var e,t,r=(e=["\n display: flex;\n "],!t&&(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}})));return O=function(){return r},r}var E=function(e){var t,r,o=e.authenticator,n=T().t,i=(0,f.useAPIClient)(),a=new URLSearchParams((0,P.useLocation)().search),c=a.get("redirect");var u=(r=(t=function(){var e,t,r;return function(e,t){var r,o,n,i,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(r)throw TypeError("Generator is already executing.");for(;a;)try{if(r=1,o&&(n=2&i[0]?o.return:i[0]?o.throw||((n=o.return)&&n.call(o),0):o.next)&&!(n=n.call(o,i[1])).done)return n;switch(o=0,n&&(i=[2&i[0],n.value]),i[0]){case 0:case 1:n=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(n=(n=a.trys).length>0&&n[n.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!n||i[1]>n[0]&&i[1]<n[3])){a.label=i[1];break}if(6===i[0]&&a.label<n[1]){a.label=n[1],n=i;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(i);break}n[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],o=0}finally{r=n=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}(this,function(n){switch(n.label){case 0:return[4,i.request({method:"post",url:"oidc:getAuthUrl",headers:{"X-Authenticator":o.name},data:{redirect:c}})];case 1:return r=null==(t=n.sent())?void 0:null===(e=t.data)||void 0===e?void 0:e.data,window.location.replace(r),[2]}})},function(){var e=this,r=arguments;return new Promise(function(o,n){var i=t.apply(e,r);function a(e){C(i,o,n,a,c,"next",e)}function c(e){C(i,o,n,a,c,"throw",e)}a(void 0)})}),function(){return r.apply(this,arguments)});return(0,x.useEffect)(function(){var e=k.get(b);if(e){var t=new URL(e);t.searchParams.set("post_logout_redirect_uri",window.location.href),k.remove(b,{domain:window.location.hostname}),window.location.href=t.href}var r=a.get("authenticator"),i=a.get("error");if(r===o.name){if(i){h.message.error(n(i));return}}}),g().createElement(h.Space,{direction:"vertical",className:(0,f.css)(O())},g().createElement(h.Button,{shape:"round",block:!0,icon:g().createElement(v.LoginOutlined,null),onClick:u},n(o.title)))},j=s("632"),R=s("505"),q={type:"object",properties:{public:{type:"object",properties:{autoSignup:{"x-decorator":"FormItem",type:"boolean",title:'{{t("Sign up automatically when the user does not exist")}}',"x-component":"Checkbox",default:!0}}},oidc:{type:"object",properties:{collapse:{type:"void","x-component":"FormTab",properties:{basic:{type:"void","x-component":"FormTab.TabPane","x-component-props":{tab:w("Basic configuration")},properties:{issuer:{type:"string",title:'{{t("Issuer")}}',"x-component":"Input","x-decorator":"FormItem",required:!0},clientId:{type:"string",title:'{{t("Client ID")}}',"x-component":"Input","x-decorator":"FormItem",required:!0},clientSecret:{type:"string",title:'{{t("Client Secret")}}',"x-component":"Input","x-decorator":"FormItem",required:!0},scope:{type:"string",title:'{{t("scope")}}',"x-component":"Input","x-decorator":"FormItem","x-decorator-props":{tooltip:'{{t("Default: openid profile email")}}'}},idTokenSignedResponseAlg:{type:"string",title:'{{t("id_token signed response algorithm")}}',"x-component":"Select","x-decorator":"FormItem",enum:[{label:"HS256",value:"HS256"},{label:"HS384",value:"HS384"},{label:"HS512",value:"HS512"},{label:"RS256",value:"RS256"},{label:"RS384",value:"RS384"},{label:"RS512",value:"RS512"},{label:"ES256",value:"ES256"},{label:"ES384",value:"ES384"},{label:"ES512",value:"ES512"},{label:"PS256",value:"PS256"},{label:"PS384",value:"PS384"},{label:"PS512",value:"PS512"}]}}},mapping:{type:"void","x-component":"FormTab.TabPane","x-component-props":{tab:w("Field mapping")},properties:{fieldMap:{title:'{{t("Field Map")}}',type:"array","x-decorator":"FormItem","x-component":"ArrayItems",items:{type:"object","x-decorator":"ArrayItems.Item",properties:{space:{type:"void","x-component":"Space",properties:{source:{type:"string","x-decorator":"FormItem","x-component":"Input","x-component-props":{placeholder:'{{t("source")}}'}},target:{type:"string","x-decorator":"FormItem","x-component":"Input","x-component-props":{placeholder:'{{t("target")}}'}},remove:{type:"void","x-decorator":"FormItem","x-component":"ArrayItems.Remove"}}}}},properties:{add:{type:"void",title:"Add","x-component":"ArrayItems.Addition"}}},userBindField:{type:"string",title:'{{t("Use this field to bind the user")}}',"x-component":"Select","x-decorator":"FormItem",default:"email",enum:[{label:w("Email"),value:"email"},{label:w("Username"),value:"username"}],required:!0}}},advanced:{type:"void","x-component":"FormTab.TabPane","x-component-props":{tab:w("Advanced configuration")},properties:{logout:{type:"boolean",title:'{{t("RP-initiated logout")}}',"x-component":"Checkbox","x-decorator":"FormItem","x-decorator-props":{tooltip:'{{t("Performs logout on the issuer (uses end_session_endpoint in the issuer configuration)")}}'}},http:{type:"boolean",title:'{{t("HTTP")}}',"x-component":"Checkbox","x-decorator":"FormItem","x-decorator-props":{tooltip:'{{t("Check if NocoBase is running on HTTP protocol")}}'}},port:{type:"number",title:'{{t("Port")}}',"x-component":"InputNumber","x-decorator":"FormItem","x-decorator-props":{tooltip:'{{t("The port number of the NocoBase service if it is not 80 or 443")}}'},"x-component-props":{style:{width:"15%",minWidth:"100px"}}},stateToken:{type:"string",title:'{{t("State token")}}',"x-component":"Input","x-decorator":"FormItem",description:w("The state token helps prevent CSRF attacks. It's recommended to leave it blank for automatic random generation.")},exchangeBodyKeys:{type:"array",title:'{{t("Pass parameters in the authorization code grant exchange")}}',"x-decorator":"FormItem","x-component":"ArrayItems",default:[{paramName:"",optionsKey:"clientId"},{paramName:"",optionsKey:"clientSecret"}],items:{type:"object","x-decorator":"ArrayItems.Item",properties:{space:{type:"void","x-component":"Space",properties:{enabled:{type:"boolean","x-decorator":"FormItem","x-component":"Checkbox"},optionsKey:{type:"string","x-decorator":"FormItem","x-decorator-props":{style:{width:"100px"}},"x-component":"Select","x-read-pretty":!0,enum:[{label:w("Client ID"),value:"clientId"},{label:w("Client Secret"),value:"clientSecret"}]},paramName:{type:"string","x-decorator":"FormItem","x-component":"Input","x-component-props":{placeholder:'{{t("Parameter name")}}'}}}}}}},userInfoMethod:{type:"string",title:'{{t("Method to call the user info endpoint")}}',"x- decorator":"FormItem","x-component":"Radio.Group",default:"GET",enum:[{label:"GET",value:"GET"},{label:"POST",value:"POST"}],"x-reactions":[{dependencies:[".accessTokenVia"],when:'{{$deps[0] === "query"}}',fulfill:{state:{value:"GET"}}},{dependencies:[".accessTokenVia"],when:'{{$deps[0] === "body"}}',fulfill:{state:{value:"POST"}}}]},accessTokenVia:{type:"string",title:'{{t("Where to put the access token when calling the user info endpoint")}}',"x- decorator":"FormItem","x-component":"Radio.Group",default:"header",enum:[{label:w("Header"),value:"header"},{label:w("Body (Use with POST method)"),value:"body"},{label:w("Query parameters (Use with GET method)"),value:"query"}]}}}}}}},usage:{type:"void","x-component":"Usage"}}},A=(0,R.observer)(function(){var e=T().t,t=(0,f.useApp)(),r=(0,x.useMemo)(function(){return t.getApiUrl("oidc:redirect")},[t]),o=function(t){navigator.clipboard.writeText(t),h.message.success(e("Copied"))};return g().createElement(h.Card,{title:e("Usage"),type:"inner"},g().createElement(f.FormItem,{label:e("Redirect URL")},g().createElement(f.Input,{value:r,disabled:!0,addonBefore:g().createElement(v.CopyOutlined,{onClick:function(){return o(r)}})})))},{displayName:"Usage"}),_=function(){var e=T().t;return g().createElement(f.SchemaComponent,{scope:{t:e},components:{Usage:A,ArrayItems:j.ArrayItems,Space:h.Space,FormTab:j.FormTab},schema:q})};function U(e,t,r,o,n,i,a){try{var c=e[i](a),u=c.value}catch(e){r(e);return}c.done?t(u):Promise.resolve(u).then(o,n)}function B(e,t,r){return(B=z()?Reflect.construct:function(e,t,r){var o=[null];o.push.apply(o,t);var n=new(Function.bind.apply(e,o));return r&&G(n,r.prototype),n}).apply(null,arguments)}function M(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function D(e){return(D=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function G(e,t){return(G=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function H(e){var t="function"==typeof Map?new Map:void 0;return(H=function(e){var r;if(null===e||(r=e,-1===Function.toString.call(r).indexOf("[native code]")))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,o)}function o(){return B(e,arguments,D(this).constructor)}return o.prototype=Object.create(e.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),G(o,e)})(e)}function z(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(z=function(){return!!e})()}var N=function(e){var t,r,o;function n(){var e,t,r;return!function(e,t){if(!(e instanceof t))throw TypeError("Cannot call a class as a function")}(this,n),e=this,t=n,r=arguments,t=D(t),function(e,t){return t&&("object"===function(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}(t)||"function"==typeof t)?t:function(e){if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,z()?Reflect.construct(t,r||[],D(e).constructor):t.apply(e,r))}return!function(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&G(e,t)}(n,e),t=n,r=[{key:"load",value:function(){var e,t=this;return(e=function(){return function(e,t){var r,o,n,i,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(r)throw TypeError("Generator is already executing.");for(;a;)try{if(r=1,o&&(n=2&i[0]?o.return:i[0]?o.throw||((n=o.return)&&n.call(o),0):o.next)&&!(n=n.call(o,i[1])).done)return n;switch(o=0,n&&(i=[2&i[0],n.value]),i[0]){case 0:case 1:n=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,o=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(n=(n=a.trys).length>0&&n[n.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!n||i[1]>n[0]&&i[1]<n[3])){a.label=i[1];break}if(6===i[0]&&a.label<n[1]){a.label=n[1],n=i;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(i);break}n[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],o=0}finally{r=n=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}(this,function(e){return t.app.pm.get(y()).registerType("OIDC+",{components:{SignInButton:E,AdminSettingsForm:_}}),[2]})},function(){var t=this,r=arguments;return new Promise(function(o,n){var i=e.apply(t,r);function a(e){U(i,o,n,a,c,"next",e)}function c(e){U(i,o,n,a,c,"throw",e)}a(void 0)})})()}}],M(t.prototype,r),n}(H(f.Plugin)),L=N;return d}()});
@@ -9,15 +9,15 @@
9
9
 
10
10
  module.exports = {
11
11
  "@ant-design/icons": "5.2.6",
12
- "@nocobase/client": "1.3.19-beta",
12
+ "@nocobase/client": "1.5.20",
13
13
  "antd": "5.12.8",
14
14
  "react": "18.2.0",
15
15
  "react-router-dom": "6.21.0",
16
- "@nocobase/plugin-auth": "1.3.19-beta",
16
+ "@nocobase/plugin-auth": "1.5.20",
17
17
  "@formily/antd-v5": "1.1.9",
18
18
  "@formily/react": "2.3.0",
19
- "@nocobase/auth": "1.3.19-beta",
20
- "@nocobase/server": "1.3.19-beta",
19
+ "@nocobase/auth": "1.5.20",
20
+ "@nocobase/server": "1.5.20",
21
21
  "react-i18next": "11.18.6",
22
- "@nocobase/actions": "1.3.19-beta"
22
+ "@nocobase/actions": "1.5.20"
23
23
  };
@@ -0,0 +1,23 @@
1
+ {
2
+ "image": "localhost/ai-opensource:latest",
3
+ "forwardPorts": [],
4
+ "mounts": [
5
+ {
6
+ "source": "pnpm-store",
7
+ "target": "/home/ai/.local/share/pnpm/store",
8
+ "type": "volume"
9
+ },
10
+ {
11
+ "source": "shell-history",
12
+ "target": "/home/ai/.local/share/history/",
13
+ "type": "volume"
14
+ }
15
+ ],
16
+ "workspaceMount": "",
17
+ "runArgs": [
18
+ "--userns=keep-id:uid=1000,gid=1000",
19
+ "--volume=${localWorkspaceFolder}:/workspaces/${localWorkspaceFolderBasename}:Z",
20
+ "--network=host",
21
+ "--ulimit=host"
22
+ ]
23
+ }
@@ -1,27 +1,61 @@
1
1
  let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
2
+
2
3
  let customAlphabet = (alphabet, defaultSize = 21) => {
4
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
5
+ // values closer to the alphabet size. The bitmask calculates the closest
6
+ // `2^31 - 1` number, which exceeds the alphabet size.
7
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
8
+ // `Math.clz32` is not used, because it is not available in browsers.
3
9
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
10
+ // Though, the bitmask solution is not perfect since the bytes exceeding
11
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
12
+ // the random bytes redundancy has to be satisfied.
13
+
14
+ // Note: every hardware random generator call is performance expensive,
15
+ // because the system call for entropy collection takes a lot of time.
16
+ // So, to avoid additional system calls, extra bytes are requested in advance.
17
+
18
+ // Next, a step determines how many random bytes to generate.
19
+ // The number of random bytes gets decided upon the ID size, mask,
20
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
21
+ // according to benchmarks).
22
+
23
+ // `-~f => Math.ceil(f)` if f is a float
24
+ // `-~i => i + 1` if i is an integer
4
25
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
26
+
5
27
  return async (size = defaultSize) => {
6
28
  let id = ''
7
29
  while (true) {
8
30
  let bytes = crypto.getRandomValues(new Uint8Array(step))
9
- let i = step
31
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
32
+ let i = step | 0
10
33
  while (i--) {
34
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
11
35
  id += alphabet[bytes[i] & mask] || ''
12
36
  if (id.length === size) return id
13
37
  }
14
38
  }
15
39
  }
16
40
  }
41
+
17
42
  let nanoid = async (size = 21) => {
18
43
  let id = ''
19
- let bytes = crypto.getRandomValues(new Uint8Array(size))
44
+ let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
45
+
46
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
20
47
  while (size--) {
48
+ // It is incorrect to use bytes exceeding the alphabet size.
49
+ // The following mask reduces the random byte in the 0-255 value
50
+ // range to the 0-63 value range. Therefore, adding hacks, such
51
+ // as empty string fallback or magic numbers, is unneccessary because
52
+ // the bitmask trims bytes down to the alphabet size.
21
53
  let byte = bytes[size] & 63
22
54
  if (byte < 36) {
55
+ // `0-9a-z`
23
56
  id += byte.toString(36)
24
57
  } else if (byte < 62) {
58
+ // `A-Z`
25
59
  id += (byte - 26).toString(36).toUpperCase()
26
60
  } else if (byte < 63) {
27
61
  id += '_'
@@ -31,4 +65,5 @@ let nanoid = async (size = 21) => {
31
65
  }
32
66
  return id
33
67
  }
68
+
34
69
  module.exports = { nanoid, customAlphabet, random }
@@ -1,27 +1,61 @@
1
1
  let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
2
+
2
3
  let customAlphabet = (alphabet, defaultSize = 21) => {
4
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
5
+ // values closer to the alphabet size. The bitmask calculates the closest
6
+ // `2^31 - 1` number, which exceeds the alphabet size.
7
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
8
+ // `Math.clz32` is not used, because it is not available in browsers.
3
9
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
10
+ // Though, the bitmask solution is not perfect since the bytes exceeding
11
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
12
+ // the random bytes redundancy has to be satisfied.
13
+
14
+ // Note: every hardware random generator call is performance expensive,
15
+ // because the system call for entropy collection takes a lot of time.
16
+ // So, to avoid additional system calls, extra bytes are requested in advance.
17
+
18
+ // Next, a step determines how many random bytes to generate.
19
+ // The number of random bytes gets decided upon the ID size, mask,
20
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
21
+ // according to benchmarks).
22
+
23
+ // `-~f => Math.ceil(f)` if f is a float
24
+ // `-~i => i + 1` if i is an integer
4
25
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
26
+
5
27
  return async (size = defaultSize) => {
6
28
  let id = ''
7
29
  while (true) {
8
30
  let bytes = crypto.getRandomValues(new Uint8Array(step))
9
- let i = step
31
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
32
+ let i = step | 0
10
33
  while (i--) {
34
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
11
35
  id += alphabet[bytes[i] & mask] || ''
12
36
  if (id.length === size) return id
13
37
  }
14
38
  }
15
39
  }
16
40
  }
41
+
17
42
  let nanoid = async (size = 21) => {
18
43
  let id = ''
19
- let bytes = crypto.getRandomValues(new Uint8Array(size))
44
+ let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
45
+
46
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
20
47
  while (size--) {
48
+ // It is incorrect to use bytes exceeding the alphabet size.
49
+ // The following mask reduces the random byte in the 0-255 value
50
+ // range to the 0-63 value range. Therefore, adding hacks, such
51
+ // as empty string fallback or magic numbers, is unneccessary because
52
+ // the bitmask trims bytes down to the alphabet size.
21
53
  let byte = bytes[size] & 63
22
54
  if (byte < 36) {
55
+ // `0-9a-z`
23
56
  id += byte.toString(36)
24
57
  } else if (byte < 62) {
58
+ // `A-Z`
25
59
  id += (byte - 26).toString(36).toUpperCase()
26
60
  } else if (byte < 63) {
27
61
  id += '_'
@@ -31,4 +65,5 @@ let nanoid = async (size = 21) => {
31
65
  }
32
66
  return id
33
67
  }
68
+
34
69
  export { nanoid, customAlphabet, random }
@@ -1,7 +1,14 @@
1
1
  let crypto = require('crypto')
2
+
2
3
  let { urlAlphabet } = require('../url-alphabet/index.cjs')
4
+
5
+ // `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
6
+ // because it is possible to use in combination with `Buffer.allocUnsafe()`.
3
7
  let random = bytes =>
4
8
  new Promise((resolve, reject) => {
9
+ // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
10
+ // Memory flushing is unnecessary since the buffer allocation itself resets
11
+ // the memory with the new bytes.
5
12
  crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
6
13
  if (err) {
7
14
  reject(err)
@@ -10,26 +17,55 @@ let random = bytes =>
10
17
  }
11
18
  })
12
19
  })
20
+
13
21
  let customAlphabet = (alphabet, defaultSize = 21) => {
22
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
23
+ // values closer to the alphabet size. The bitmask calculates the closest
24
+ // `2^31 - 1` number, which exceeds the alphabet size.
25
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
14
26
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
27
+ // Though, the bitmask solution is not perfect since the bytes exceeding
28
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
29
+ // the random bytes redundancy has to be satisfied.
30
+
31
+ // Note: every hardware random generator call is performance expensive,
32
+ // because the system call for entropy collection takes a lot of time.
33
+ // So, to avoid additional system calls, extra bytes are requested in advance.
34
+
35
+ // Next, a step determines how many random bytes to generate.
36
+ // The number of random bytes gets decided upon the ID size, mask,
37
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
38
+ // according to benchmarks).
15
39
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
40
+
16
41
  let tick = (id, size = defaultSize) =>
17
42
  random(step).then(bytes => {
43
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
18
44
  let i = step
19
45
  while (i--) {
46
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
20
47
  id += alphabet[bytes[i] & mask] || ''
21
- if (id.length === size) return id
48
+ if (id.length >= size) return id
22
49
  }
23
50
  return tick(id, size)
24
51
  })
52
+
25
53
  return size => tick('', size)
26
54
  }
55
+
27
56
  let nanoid = (size = 21) =>
28
- random(size).then(bytes => {
57
+ random((size |= 0)).then(bytes => {
29
58
  let id = ''
59
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
30
60
  while (size--) {
61
+ // It is incorrect to use bytes exceeding the alphabet size.
62
+ // The following mask reduces the random byte in the 0-255 value
63
+ // range to the 0-63 value range. Therefore, adding hacks, such
64
+ // as empty string fallback or magic numbers, is unneccessary because
65
+ // the bitmask trims bytes down to the alphabet size.
31
66
  id += urlAlphabet[bytes[size] & 63]
32
67
  }
33
68
  return id
34
69
  })
70
+
35
71
  module.exports = { nanoid, customAlphabet, random }
@@ -1,7 +1,14 @@
1
1
  import crypto from 'crypto'
2
+
2
3
  import { urlAlphabet } from '../url-alphabet/index.js'
4
+
5
+ // `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
6
+ // because it is possible to use in combination with `Buffer.allocUnsafe()`.
3
7
  let random = bytes =>
4
8
  new Promise((resolve, reject) => {
9
+ // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
10
+ // Memory flushing is unnecessary since the buffer allocation itself resets
11
+ // the memory with the new bytes.
5
12
  crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
6
13
  if (err) {
7
14
  reject(err)
@@ -10,26 +17,55 @@ let random = bytes =>
10
17
  }
11
18
  })
12
19
  })
20
+
13
21
  let customAlphabet = (alphabet, defaultSize = 21) => {
22
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
23
+ // values closer to the alphabet size. The bitmask calculates the closest
24
+ // `2^31 - 1` number, which exceeds the alphabet size.
25
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
14
26
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
27
+ // Though, the bitmask solution is not perfect since the bytes exceeding
28
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
29
+ // the random bytes redundancy has to be satisfied.
30
+
31
+ // Note: every hardware random generator call is performance expensive,
32
+ // because the system call for entropy collection takes a lot of time.
33
+ // So, to avoid additional system calls, extra bytes are requested in advance.
34
+
35
+ // Next, a step determines how many random bytes to generate.
36
+ // The number of random bytes gets decided upon the ID size, mask,
37
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
38
+ // according to benchmarks).
15
39
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
40
+
16
41
  let tick = (id, size = defaultSize) =>
17
42
  random(step).then(bytes => {
43
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
18
44
  let i = step
19
45
  while (i--) {
46
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
20
47
  id += alphabet[bytes[i] & mask] || ''
21
- if (id.length === size) return id
48
+ if (id.length >= size) return id
22
49
  }
23
50
  return tick(id, size)
24
51
  })
52
+
25
53
  return size => tick('', size)
26
54
  }
55
+
27
56
  let nanoid = (size = 21) =>
28
- random(size).then(bytes => {
57
+ random((size |= 0)).then(bytes => {
29
58
  let id = ''
59
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
30
60
  while (size--) {
61
+ // It is incorrect to use bytes exceeding the alphabet size.
62
+ // The following mask reduces the random byte in the 0-255 value
63
+ // range to the 0-63 value range. Therefore, adding hacks, such
64
+ // as empty string fallback or magic numbers, is unneccessary because
65
+ // the bitmask trims bytes down to the alphabet size.
31
66
  id += urlAlphabet[bytes[size] & 63]
32
67
  }
33
68
  return id
34
69
  })
70
+
35
71
  export { nanoid, customAlphabet, random }
@@ -1,26 +1,57 @@
1
1
  import { getRandomBytesAsync } from 'expo-random'
2
+
2
3
  import { urlAlphabet } from '../url-alphabet/index.js'
4
+
3
5
  let random = getRandomBytesAsync
6
+
4
7
  let customAlphabet = (alphabet, defaultSize = 21) => {
8
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
9
+ // values closer to the alphabet size. The bitmask calculates the closest
10
+ // `2^31 - 1` number, which exceeds the alphabet size.
11
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
5
12
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
13
+ // Though, the bitmask solution is not perfect since the bytes exceeding
14
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
15
+ // the random bytes redundancy has to be satisfied.
16
+
17
+ // Note: every hardware random generator call is performance expensive,
18
+ // because the system call for entropy collection takes a lot of time.
19
+ // So, to avoid additional system calls, extra bytes are requested in advance.
20
+
21
+ // Next, a step determines how many random bytes to generate.
22
+ // The number of random bytes gets decided upon the ID size, mask,
23
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
24
+ // according to benchmarks).
6
25
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
26
+
7
27
  let tick = (id, size = defaultSize) =>
8
28
  random(step).then(bytes => {
29
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
9
30
  let i = step
10
31
  while (i--) {
32
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
11
33
  id += alphabet[bytes[i] & mask] || ''
12
- if (id.length === size) return id
34
+ if (id.length >= size) return id
13
35
  }
14
36
  return tick(id, size)
15
37
  })
38
+
16
39
  return size => tick('', size)
17
40
  }
41
+
18
42
  let nanoid = (size = 21) =>
19
- random(size).then(bytes => {
43
+ random((size |= 0)).then(bytes => {
20
44
  let id = ''
45
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
21
46
  while (size--) {
47
+ // It is incorrect to use bytes exceeding the alphabet size.
48
+ // The following mask reduces the random byte in the 0-255 value
49
+ // range to the 0-63 value range. Therefore, adding hacks, such
50
+ // as empty string fallback or magic numbers, is unneccessary because
51
+ // the bitmask trims bytes down to the alphabet size.
22
52
  id += urlAlphabet[bytes[size] & 63]
23
53
  }
24
54
  return id
25
55
  })
56
+
26
57
  export { nanoid, customAlphabet, random }
@@ -1,28 +1,65 @@
1
+ // This file replaces `index.js` in bundlers like webpack or Rollup,
2
+ // according to `browser` config in `package.json`.
3
+
1
4
  let { urlAlphabet } = require('./url-alphabet/index.cjs')
5
+
2
6
  let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
7
+
3
8
  let customRandom = (alphabet, defaultSize, getRandom) => {
9
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
10
+ // values closer to the alphabet size. The bitmask calculates the closest
11
+ // `2^31 - 1` number, which exceeds the alphabet size.
12
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
13
+ // `Math.clz32` is not used, because it is not available in browsers.
4
14
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
15
+ // Though, the bitmask solution is not perfect since the bytes exceeding
16
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
17
+ // the random bytes redundancy has to be satisfied.
18
+
19
+ // Note: every hardware random generator call is performance expensive,
20
+ // because the system call for entropy collection takes a lot of time.
21
+ // So, to avoid additional system calls, extra bytes are requested in advance.
22
+
23
+ // Next, a step determines how many random bytes to generate.
24
+ // The number of random bytes gets decided upon the ID size, mask,
25
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
26
+ // according to benchmarks).
27
+
28
+ // `-~f => Math.ceil(f)` if f is a float
29
+ // `-~i => i + 1` if i is an integer
5
30
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
31
+
6
32
  return (size = defaultSize) => {
7
33
  let id = ''
8
34
  while (true) {
9
35
  let bytes = getRandom(step)
10
- let j = step
36
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
37
+ let j = step | 0
11
38
  while (j--) {
39
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
12
40
  id += alphabet[bytes[j] & mask] || ''
13
41
  if (id.length === size) return id
14
42
  }
15
43
  }
16
44
  }
17
45
  }
46
+
18
47
  let customAlphabet = (alphabet, size = 21) =>
19
48
  customRandom(alphabet, size, random)
49
+
20
50
  let nanoid = (size = 21) =>
21
51
  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
52
+ // It is incorrect to use bytes exceeding the alphabet size.
53
+ // The following mask reduces the random byte in the 0-255 value
54
+ // range to the 0-63 value range. Therefore, adding hacks, such
55
+ // as empty string fallback or magic numbers, is unneccessary because
56
+ // the bitmask trims bytes down to the alphabet size.
22
57
  byte &= 63
23
58
  if (byte < 36) {
59
+ // `0-9a-z`
24
60
  id += byte.toString(36)
25
61
  } else if (byte < 62) {
62
+ // `A-Z`
26
63
  id += (byte - 26).toString(36).toUpperCase()
27
64
  } else if (byte > 62) {
28
65
  id += '-'
@@ -31,4 +68,5 @@ let nanoid = (size = 21) =>
31
68
  }
32
69
  return id
33
70
  }, '')
71
+
34
72
  module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
@@ -1,28 +1,65 @@
1
+ // This file replaces `index.js` in bundlers like webpack or Rollup,
2
+ // according to `browser` config in `package.json`.
3
+
1
4
  import { urlAlphabet } from './url-alphabet/index.js'
5
+
2
6
  let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
7
+
3
8
  let customRandom = (alphabet, defaultSize, getRandom) => {
9
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
10
+ // values closer to the alphabet size. The bitmask calculates the closest
11
+ // `2^31 - 1` number, which exceeds the alphabet size.
12
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
13
+ // `Math.clz32` is not used, because it is not available in browsers.
4
14
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
15
+ // Though, the bitmask solution is not perfect since the bytes exceeding
16
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
17
+ // the random bytes redundancy has to be satisfied.
18
+
19
+ // Note: every hardware random generator call is performance expensive,
20
+ // because the system call for entropy collection takes a lot of time.
21
+ // So, to avoid additional system calls, extra bytes are requested in advance.
22
+
23
+ // Next, a step determines how many random bytes to generate.
24
+ // The number of random bytes gets decided upon the ID size, mask,
25
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
26
+ // according to benchmarks).
27
+
28
+ // `-~f => Math.ceil(f)` if f is a float
29
+ // `-~i => i + 1` if i is an integer
5
30
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
31
+
6
32
  return (size = defaultSize) => {
7
33
  let id = ''
8
34
  while (true) {
9
35
  let bytes = getRandom(step)
10
- let j = step
36
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
37
+ let j = step | 0
11
38
  while (j--) {
39
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
12
40
  id += alphabet[bytes[j] & mask] || ''
13
41
  if (id.length === size) return id
14
42
  }
15
43
  }
16
44
  }
17
45
  }
46
+
18
47
  let customAlphabet = (alphabet, size = 21) =>
19
48
  customRandom(alphabet, size, random)
49
+
20
50
  let nanoid = (size = 21) =>
21
51
  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
52
+ // It is incorrect to use bytes exceeding the alphabet size.
53
+ // The following mask reduces the random byte in the 0-255 value
54
+ // range to the 0-63 value range. Therefore, adding hacks, such
55
+ // as empty string fallback or magic numbers, is unneccessary because
56
+ // the bitmask trims bytes down to the alphabet size.
22
57
  byte &= 63
23
58
  if (byte < 36) {
59
+ // `0-9a-z`
24
60
  id += byte.toString(36)
25
61
  } else if (byte < 62) {
62
+ // `A-Z`
26
63
  id += (byte - 26).toString(36).toUpperCase()
27
64
  } else if (byte > 62) {
28
65
  id += '-'
@@ -31,4 +68,5 @@ let nanoid = (size = 21) =>
31
68
  }
32
69
  return id
33
70
  }, '')
71
+
34
72
  export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
@@ -1 +1 @@
1
- (function(){var e={113:function(e){"use strict";e.exports=require("crypto")},592:function(e,t,r){let l=r(113);let{urlAlphabet:n}=r(651);const a=128;let u,i;let fillPool=e=>{if(!u||u.length<e){u=Buffer.allocUnsafe(e*a);l.randomFillSync(u);i=0}else if(i+e>u.length){l.randomFillSync(u);i=0}i+=e};let random=e=>{fillPool(e-=0);return u.subarray(i-e,i)};let customRandom=(e,t,r)=>{let l=(2<<31-Math.clz32(e.length-1|1))-1;let n=Math.ceil(1.6*l*t/e.length);return(a=t)=>{let u="";while(true){let t=r(n);let i=n;while(i--){u+=e[t[i]&l]||"";if(u.length===a)return u}}}};let customAlphabet=(e,t=21)=>customRandom(e,t,random);let nanoid=(e=21)=>{fillPool(e-=0);let t="";for(let r=i-e;r<i;r++){t+=n[u[r]&63]}return t};e.exports={nanoid:nanoid,customAlphabet:customAlphabet,customRandom:customRandom,urlAlphabet:n,random:random}},651:function(e){let t="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";e.exports={urlAlphabet:t}}};var t={};function __nccwpck_require__(r){var l=t[r];if(l!==undefined){return l.exports}var n=t[r]={exports:{}};var a=true;try{e[r](n,n.exports,__nccwpck_require__);a=false}finally{if(a)delete t[r]}return n.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(592);module.exports=r})();
1
+ (function(){var e={113:function(e){"use strict";e.exports=require("crypto")},775:function(e,t,r){let l=r(113);let{urlAlphabet:n}=r(265);const a=128;let u,i;let fillPool=e=>{if(!u||u.length<e){u=Buffer.allocUnsafe(e*a);l.randomFillSync(u);i=0}else if(i+e>u.length){l.randomFillSync(u);i=0}i+=e};let random=e=>{fillPool(e|=0);return u.subarray(i-e,i)};let customRandom=(e,t,r)=>{let l=(2<<31-Math.clz32(e.length-1|1))-1;let n=Math.ceil(1.6*l*t/e.length);return(a=t)=>{let u="";while(true){let t=r(n);let i=n;while(i--){u+=e[t[i]&l]||"";if(u.length===a)return u}}}};let customAlphabet=(e,t=21)=>customRandom(e,t,random);let nanoid=(e=21)=>{fillPool(e|=0);let t="";for(let r=i-e;r<i;r++){t+=n[u[r]&63]}return t};e.exports={nanoid:nanoid,customAlphabet:customAlphabet,customRandom:customRandom,urlAlphabet:n,random:random}},265:function(e){let t="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";e.exports={urlAlphabet:t}}};var t={};function __nccwpck_require__(r){var l=t[r];if(l!==undefined){return l.exports}var n=t[r]={exports:{}};var a=true;try{e[r](n,n.exports,__nccwpck_require__);a=false}finally{if(a)delete t[r]}return n.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(775);module.exports=r})();