feat(core,extensions): 구동 에셋 자체 제공 · 자산 실패 폴백 · 운영자 추가 에셋(custom/)
공개 저장소 이슈 gnuboard/g7 (@bigmsg) 제보에서 출발한 작업이다. 브라우저가 화면을 그리려고 제3자 CDN 에 도달해야 하면, 그 도달 실패는 예외도 로그도 남기지 않고 화면 기능만 조용히 사라진다. 폐쇄망·방화벽·광고차단기에서 재현되는데 자체 서버 로그에는 흔적이 없어 운영자가 원인을 특정할 수 없다. 제보된 것은 편집기 하나였지만 같은 구조가 아이콘·글꼴·코드편집기·압축 라이브러리·설치 마법사·개발 대시보드에 똑같이 있었으므로, 번들 확장과 템플릿 전체를 자체 제공으로 옮겼다. 런타임에 외부로 나가는 것은 주소 검색 서비스 하나만 남았다. 자체 제공만으로는 부족하다 — 자기 서버에서 받는 파일도 실패할 수 있고, 종전에는 그 실패가 무음이었다. CSS 경로에 재시도 계층을 세우고(스크립트 경로와 동형), 서버가 HTML 에 직접 심는 externals 까지 실패를 붙잡아 안내 배너와 [다시 시도]로 표면화했다. 편집기·코드편집기는 확보 실패 시 평문 입력으로 내려앉되 저장 계약을 유지한다. 두 번째 축은 운영자가 CSS 를 덧붙일 자리가 없던 문제다(sir.kr 문의). 확장 디렉토리의 custom/ 을 운영자 소유로 정해, 확장 교체가 그 디렉토리만은 보존하게 했다. 출처에 의존하지 않는 서술자로 해석하므로 나중에 다른 출처가 붙어도 소비자는 바뀌지 않는다. 확장 자산과 같은 메커니즘으로 정적 게시되어 CSS 내부 상대 url 도 해석되고, 파일을 고치면 그 변경을 감지해 재게시까지 예약된다. FTP 접근이 없는 운영자에게는 그 자리도 없는 것과 같으므로 레이아웃 편집기에서 직접 넣고 고칠 수 있게 했다. 모듈·플러그인·템플릿이 한 엔드포인트를 공유한다 — 타입별로 나누면 같은 검증이 세 벌로 갈리고 그중 약한 하나가 우회로가 된다. 여기서 올린 스크립트는 그 레이아웃 한 장이 아니라 사이트 전 화면에서 실행되므로 레이아웃 편집과 분리된 전용 권한으로 연다. 운영자 CSS 가 화면을 조작 불능으로 만들면 그것을 고칠 화면에도 같은 CSS 가 실려 스스로 갇히므로, 서버가 목록을 비우는 탈출구(?custom=off)를 함께 뒀다. 동봉 자산은 재생성 경로에 버전 대조 가드를 붙였다. 선언과 다른 버전을 버전 디렉토리에 써 넣는 조용한 거짓말은 배포된 뒤에는 드러나지 않는다.
This commit is contained in:
1 parent
72f2e94c1a
commit
3945b6f1b3
1042 files changed
+107435
-947
No files matched your search
@@ -4,6 +4,13 @@
|
||||
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
|
||||
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
|
||||
|
||||
## [1.0.3] - 2026-08-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- 주소 검색 서비스를 불러오지 못한 상태에서 우편번호·주소 입력란이 읽기 전용으로 고정되어, 검색도 직접 입력도 할 수 없던 문제를 고쳤습니다. 이제 검색을 쓸 수 있을 때만 읽기 전용이 되고, 그렇지 않으면 직접 입력할 수 있습니다.
|
||||
- [주소 검색] 버튼이 아무 반응도 없던 경우에 안내와 [다시 시도] 를 표시합니다. 종전에는 클릭이 먹지 않는 것으로만 보였습니다.
|
||||
|
||||
## [1.0.2] - 2026-08-19
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"identifier": "sirsoft-daum_postcode",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.3",
|
||||
"components": {
|
||||
"basic": [],
|
||||
"composite": [],
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "plugins/sirsoft-daum_postcode",
|
||||
"description": "Daum Postcode Service Plugin for Gnuboard7 platform",
|
||||
"type": "library",
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.3",
|
||||
"authors": [
|
||||
{
|
||||
"name": "sirsoft",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
var SirsoftDaumPostcode=function(m){"use strict";const y=window.G7Core?.createLogger?.("DaumPostcode:SetFieldReadOnly")??{log:(...e)=>console.log("[DaumPostcode:SetFieldReadOnly]",...e),warn:(...e)=>console.warn("[DaumPostcode:SetFieldReadOnly]",...e),error:(...e)=>console.error("[DaumPostcode:SetFieldReadOnly]",...e)};function C(e,c){const o=e.params||{},t=o.fields||[],n=o.readOnly!==!1;if(!t.length){y.warn("[setFieldReadOnly] No fields specified");return}y.log(`[setFieldReadOnly] Setting readOnly=${n} for fields:`,t),t.forEach(r=>{const s=document.querySelectorAll(`input[name="${r}"], textarea[name="${r}"]`);if(s.length===0){y.warn(`[setFieldReadOnly] No input found with name="${r}"`);return}s.forEach(i=>{i.readOnly=n,n?i.classList.add("readonly"):i.classList.remove("readonly"),y.log(`[setFieldReadOnly] Set readOnly=${n} on input[name="${r}"]`)})})}const a=window.G7Core?.createLogger?.("DaumPostcode:OpenPostcode")??{log:(...e)=>console.log("[DaumPostcode:OpenPostcode]",...e),warn:(...e)=>console.warn("[DaumPostcode:OpenPostcode]",...e),error:(...e)=>console.error("[DaumPostcode:OpenPostcode]",...e)};function O(e){return{zipcode:e.zonecode||"",address:e.roadAddress||e.jibunAddress||"",addressDetail:"",region:e.sido||"",city:e.sigungu||"",countryCode:"KR",_raw:e}}function x(e,c){const o=e.params||{},{callbackAction:t,displayMode:n="layer",width:r=500,height:s=600,theme:i,targetFields:l}=o,b=(window.G7Core?.plugin?.getSettings?.("sirsoft-daum_postcode")||{}).target_fields||{zipcode:"shipping.zipcode",address:"shipping.address",region:"shipping.region",city:"shipping.city"};if(a.log("[openPostcode] Starting with params:",{displayMode:n,width:r,height:s,hasCallbackAction:!!t,targetFields:l||b}),!window.daum?.Postcode){a.error("[openPostcode] Daum Postcode API not loaded");return}const g={oncomplete:h=>{a.log("[openPostcode] Address selected (raw):",h);const f=O(h);a.log("[openPostcode] Converted to G7 format:",f),t?(a.log("[openPostcode] Executing callbackAction"),L(t,f,c)):(a.log("[openPostcode] Executing default setState"),S(l||b,f))},width:r,height:s};i&&(g.theme=i);const v=new window.daum.Postcode(g);if(n==="popup")v.open();else{const{layer:h,closeLayer:f}=$(r,s),D=g.oncomplete;g.oncomplete=k=>{f(),D(k)},new window.daum.Postcode(g).embed(h)}}function $(e,c){const o=document.createElement("div");o.id="daum-postcode-overlay",o.style.cssText=`
|
||||
var SirsoftDaumPostcode=function(h){"use strict";const L="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js",P="daum_postcode_script",D="daum-postcode-sdk";function O(e,n){const o=window?.G7Core?.t;if(typeof o!="function")return n;const t=`sirsoft-daum_postcode.${e}`,s=o(t);return typeof s=="string"&&s!==t?s:n}function p(){return!!window.daum?.Postcode}function A(e=12e3){return p()?Promise.resolve(!0):new Promise(n=>{const o=Date.now(),t=()=>{if(p()){n(!0);return}if(Date.now()-o>=e){n(!1);return}setTimeout(t,100)};setTimeout(t,100)})}async function _(){if(p())return!0;document.getElementById(P)?.remove();const e=window?.G7Core?.asset?.loadScript;try{typeof e=="function"?await e(L,{id:P},{label:"daum postcode SDK"}):await new Promise((n,o)=>{const t=document.createElement("script");t.id=P,t.src=L,t.onload=()=>n(),t.onerror=()=>o(new Error("daum postcode SDK load failed")),document.head.appendChild(t)})}catch{return!1}return p()}function E(e){const n=window?.G7Core?.assets?.notifyFailure,o=O("postcode.error.sdk_unavailable","주소 검색을 불러오지 못했습니다. 주소를 직접 입력해 주세요.");if(typeof n!="function"){console.warn(`[sirsoft-daum_postcode] ${o}`);return}n({id:D,label:O("postcode.search","주소 검색"),message:o,retry:async()=>{if(!await _())throw new Error("[sirsoft-daum_postcode] 주소 검색을 여전히 불러올 수 없습니다.");await e()}})}function S(){window?.G7Core?.assets?.clearFailure?.(D)}const f=window.G7Core?.createLogger?.("DaumPostcode:SetFieldReadOnly")??{log:(...e)=>console.log("[DaumPostcode:SetFieldReadOnly]",...e),warn:(...e)=>console.warn("[DaumPostcode:SetFieldReadOnly]",...e),error:(...e)=>console.error("[DaumPostcode:SetFieldReadOnly]",...e)};async function k(e,n){const o=e.params||{},t=o.fields||[],s=o.readOnly!==!1;if(!t.length){f.warn("[setFieldReadOnly] No fields specified");return}if(s){if(!await A(o.sdkWaitMs)){f.warn("[setFieldReadOnly] Daum Postcode SDK unavailable — leaving fields editable"),b(t,!1),E(()=>{b(t,!0),S()});return}S()}f.log(`[setFieldReadOnly] Setting readOnly=${s} for fields:`,t),b(t,s)}function b(e,n){e.forEach(o=>{const t=document.querySelectorAll(`input[name="${o}"], textarea[name="${o}"]`);if(t.length===0){f.warn(`[setFieldReadOnly] No input found with name="${o}"`);return}t.forEach(s=>{s.readOnly=n,n?s.classList.add("readonly"):s.classList.remove("readonly"),f.log(`[setFieldReadOnly] Set readOnly=${n} on input[name="${o}"]`)})})}const i=window.G7Core?.createLogger?.("DaumPostcode:OpenPostcode")??{log:(...e)=>console.log("[DaumPostcode:OpenPostcode]",...e),warn:(...e)=>console.warn("[DaumPostcode:OpenPostcode]",...e),error:(...e)=>console.error("[DaumPostcode:OpenPostcode]",...e)};function R(e){return{zipcode:e.zonecode||"",address:e.roadAddress||e.jibunAddress||"",addressDetail:"",region:e.sido||"",city:e.sigungu||"",countryCode:"KR",_raw:e}}async function $(e,n){const o=e.params||{},{callbackAction:t,displayMode:s="layer",width:c=500,height:r=600,theme:a,targetFields:l}=o,x=(window.G7Core?.plugin?.getSettings?.("sirsoft-daum_postcode")||{}).target_fields||{zipcode:"shipping.zipcode",address:"shipping.address",region:"shipping.region",city:"shipping.city"};if(i.log("[openPostcode] Starting with params:",{displayMode:s,width:c,height:r,hasCallbackAction:!!t,targetFields:l||x}),!p()){if(i.warn("[openPostcode] Daum Postcode API not loaded — retrying"),!await _()){i.error("[openPostcode] Daum Postcode API unavailable"),E(()=>$(e,n));return}S()}const y={oncomplete:w=>{i.log("[openPostcode] Address selected (raw):",w);const m=R(w);i.log("[openPostcode] Converted to G7 format:",m),t?(i.log("[openPostcode] Executing callbackAction"),G(t,m,n)):(i.log("[openPostcode] Executing default setState"),F(l||x,m))},width:c,height:r};a&&(y.theme=a);const I=new window.daum.Postcode(y);if(s==="popup")I.open();else{const{layer:w,closeLayer:m}=T(c,r),j=y.oncomplete;y.oncomplete=M=>{m(),j(M)},new window.daum.Postcode(y).embed(w)}}function T(e,n){const o=document.createElement("div");o.id="daum-postcode-overlay",o.style.cssText=`
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
@@ -11,12 +11,12 @@ var SirsoftDaumPostcode=function(m){"use strict";const y=window.G7Core?.createLo
|
||||
z-index: 9999;
|
||||
`;const t=document.createElement("div");t.id="daum-postcode-layer",t.style.cssText=`
|
||||
width: ${e}px;
|
||||
height: ${c}px;
|
||||
height: ${n}px;
|
||||
background-color: white;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
|
||||
`;const n=document.createElement("button");n.type="button",n.innerHTML="×",n.style.cssText=`
|
||||
`;const s=document.createElement("button");s.type="button",s.innerHTML="×",s.style.cssText=`
|
||||
position: absolute;
|
||||
top: -12px;
|
||||
right: -12px;
|
||||
@@ -33,4 +33,4 @@ var SirsoftDaumPostcode=function(m){"use strict";const y=window.G7Core?.createLo
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10;
|
||||
`;const r=document.createElement("div");r.style.cssText="position: relative;",r.appendChild(n),r.appendChild(t),o.appendChild(r),document.body.appendChild(o);const s=()=>{o.parentNode&&o.parentNode.removeChild(o)};n.addEventListener("click",s),o.addEventListener("click",l=>{l.target===o&&s()});const i=l=>{l.key==="Escape"&&(s(),document.removeEventListener("keydown",i))};return document.addEventListener("keydown",i),a.log("[openPostcode] Layer created with size:",{width:e,height:c}),{overlay:o,layer:t,closeLayer:s}}function L(e,c,o){const t=window.G7Core;if(!t?.dispatch){a.error("[openPostcode] G7Core.dispatch not available");return}const n=o?.state||t?.state?.getLocal?.()||{},r={state:n,setState:o?.setState,data:{...o?.data||{},_local:n,$event:c},isolatedContext:o?.isolatedContext};a.log("[openPostcode] Dispatching with componentContext:",{hasLocalState:!!n,sourceType:o?.state?"handlerContext":"getLocal",localCheckout:n?.checkout,event:c});try{const s=Array.isArray(e)?e:[e];for(const i of s)i&&typeof i=="object"&&(a.log("[openPostcode] Dispatching action:",i),t.dispatch(i,{componentContext:r}))}catch(s){a.error("[openPostcode] callbackAction failed:",s)}}function S(e,c){const o=window.G7Core;if(!o?.state?.setLocal){a.error("[openPostcode] G7Core.state.setLocal not available");return}const t={};e.zipcode&&(t[e.zipcode]=c.zipcode),e.address&&(t[e.address]=c.address),e.region&&(t[e.region]=c.region),e.city&&(t[e.city]=c.city),a.log("[openPostcode] Setting local state:",t),o.state.setLocal(t)}const p={setFieldReadOnly:C,openPostcode:x},d="sirsoft-daum_postcode",u=window.G7Core?.createLogger?.(`Plugin:${d}`)??{log:(...e)=>console.log(`[Plugin:${d}]`,...e),warn:(...e)=>console.warn(`[Plugin:${d}]`,...e),error:(...e)=>console.error(`[Plugin:${d}]`,...e)};function P(e=!1){const c=window.G7Core?.getActionDispatcher?.();if(c)Object.entries(p).forEach(([o,t])=>{const n=`${d}.${o}`;c.registerHandler(n,t,{category:"plugin",source:d})}),u.log(`${Object.keys(p).length} handler(s) registered:`,Object.keys(p).map(o=>`${d}.${o}`));else if(e){let o=0;const t=50,n=()=>{const r=window.G7Core?.getActionDispatcher?.();r?(Object.entries(p).forEach(([s,i])=>{const l=`${d}.${s}`;r.registerHandler(l,i,{category:"plugin",source:d})}),u.log(`${Object.keys(p).length} handler(s) registered:`,Object.keys(p).map(s=>`${d}.${s}`))):(o++,o<=t?(u.warn(`ActionDispatcher not found, retrying... (${o}/${t})`),setTimeout(n,100)):u.error("Failed to register handlers: ActionDispatcher not available after maximum retries"))};n()}else u.warn("ActionDispatcher not found, handlers not registered")}function w(){if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>P(!0));else{const e=!!window.G7Core?.getActionDispatcher?.();P(!e)}}return w(),typeof window<"u"&&(window.__SirsoftDaumPostcode={identifier:d,handlers:Object.keys(p),initPlugin:w}),m.initPlugin=w,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"}),m}({});
|
||||
`;const c=document.createElement("div");c.style.cssText="position: relative;",c.appendChild(s),c.appendChild(t),o.appendChild(c),document.body.appendChild(o);const r=()=>{o.parentNode&&o.parentNode.removeChild(o)};s.addEventListener("click",r),o.addEventListener("click",l=>{l.target===o&&r()});const a=l=>{l.key==="Escape"&&(r(),document.removeEventListener("keydown",a))};return document.addEventListener("keydown",a),i.log("[openPostcode] Layer created with size:",{width:e,height:n}),{overlay:o,layer:t,closeLayer:r}}function G(e,n,o){const t=window.G7Core;if(!t?.dispatch){i.error("[openPostcode] G7Core.dispatch not available");return}const s=o?.state||t?.state?.getLocal?.()||{},c={state:s,setState:o?.setState,data:{...o?.data||{},_local:s,$event:n},isolatedContext:o?.isolatedContext};i.log("[openPostcode] Dispatching with componentContext:",{hasLocalState:!!s,sourceType:o?.state?"handlerContext":"getLocal",localCheckout:s?.checkout,event:n});try{const r=Array.isArray(e)?e:[e];for(const a of r)a&&typeof a=="object"&&(i.log("[openPostcode] Dispatching action:",a),t.dispatch(a,{componentContext:c}))}catch(r){i.error("[openPostcode] callbackAction failed:",r)}}function F(e,n){const o=window.G7Core;if(!o?.state?.setLocal){i.error("[openPostcode] G7Core.state.setLocal not available");return}const t={};e.zipcode&&(t[e.zipcode]=n.zipcode),e.address&&(t[e.address]=n.address),e.region&&(t[e.region]=n.region),e.city&&(t[e.city]=n.city),i.log("[openPostcode] Setting local state:",t),o.state.setLocal(t)}const u={setFieldReadOnly:k,openPostcode:$},d="sirsoft-daum_postcode",g=window.G7Core?.createLogger?.(`Plugin:${d}`)??{log:(...e)=>console.log(`[Plugin:${d}]`,...e),warn:(...e)=>console.warn(`[Plugin:${d}]`,...e),error:(...e)=>console.error(`[Plugin:${d}]`,...e)};function v(e=!1){const n=window.G7Core?.getActionDispatcher?.();if(n)Object.entries(u).forEach(([o,t])=>{const s=`${d}.${o}`;n.registerHandler(s,t,{category:"plugin",source:d})}),g.log(`${Object.keys(u).length} handler(s) registered:`,Object.keys(u).map(o=>`${d}.${o}`));else if(e){let o=0;const t=50,s=()=>{const c=window.G7Core?.getActionDispatcher?.();c?(Object.entries(u).forEach(([r,a])=>{const l=`${d}.${r}`;c.registerHandler(l,a,{category:"plugin",source:d})}),g.log(`${Object.keys(u).length} handler(s) registered:`,Object.keys(u).map(r=>`${d}.${r}`))):(o++,o<=t?(g.warn(`ActionDispatcher not found, retrying... (${o}/${t})`),setTimeout(s,100)):g.error("Failed to register handlers: ActionDispatcher not available after maximum retries"))};s()}else g.warn("ActionDispatcher not found, handlers not registered")}function C(){if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>v(!0));else{const e=!!window.G7Core?.getActionDispatcher?.();v(!e)}}return C(),typeof window<"u"&&(window.__SirsoftDaumPostcode={identifier:d,handlers:Object.keys(u),initPlugin:C}),h.initPlugin=C,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"}),h}({});
|
||||
+1023
-3
File diff suppressed because it is too large.
Load diff
@@ -1,16 +1,20 @@
|
||||
{
|
||||
"name": "@g7/sirsoft-daum_postcode",
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.3",
|
||||
"description": "그누보드7 Daum 우편번호 플러그인 프론트엔드 에셋",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.3.3",
|
||||
"vite": "^5.4.14"
|
||||
"vite": "^5.4.14",
|
||||
"jsdom": "^27.4.0",
|
||||
"vitest": "^2.1.8"
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,13 @@
|
||||
"ko": "Daum 우편번호",
|
||||
"en": "Daum Postcode"
|
||||
},
|
||||
"version": "1.0.2",
|
||||
"version": "1.0.3",
|
||||
"license": "MIT",
|
||||
"description": {
|
||||
"ko": "Daum 우편번호 서비스를 통한 주소 검색 기능을 제공하는 플러그인입니다. API 키 없이 무료로 사용할 수 있습니다.",
|
||||
"en": "Plugin that provides address search functionality through Daum Postcode service. Free to use without API key."
|
||||
},
|
||||
"g7_version": ">=7.0.7",
|
||||
"g7_version": ">=7.0.10",
|
||||
"dependencies": {
|
||||
"modules": {},
|
||||
"plugins": {}
|
||||
@@ -31,5 +31,8 @@
|
||||
"loading": {
|
||||
"strategy": "global",
|
||||
"priority": 100
|
||||
},
|
||||
"trusted_script_hosts_reason": {
|
||||
"t1.daumcdn.net": "다음 우편번호는 라이브러리가 아니라 Daum 이 운영하는 서비스 SDK 다. 스크립트가 Daum 서버와 통신하므로 자체 호스팅해도 동작하지 않는다. 대신 SDK 를 못 불러오면 주소를 직접 입력할 수 있게 한다."
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* 우편번호 SDK 미확보 시의 입력 가능 상태 보장
|
||||
*
|
||||
* 종전에는 `setFieldReadOnly` 가 SDK 확보 여부와 무관하게 마운트 시점에 필드를
|
||||
* 읽기 전용으로 고정했다. 검색 버튼도 SDK 가 없으면 무반응이라, 둘이 겹치면
|
||||
* 주소를 검색할 수도 직접 입력할 수도 없어 주문을 끝낼 수 없었다.
|
||||
*
|
||||
* @scenario asset_class=service_sdk, outcome=failed
|
||||
* @effects address_fields_editable_when_sdk_missing, failed_asset_shows_retry_notice
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { setFieldReadOnlyHandler } from '../handlers/setFieldReadOnly';
|
||||
import { isPostcodeSdkReady, waitForPostcodeSdk } from '../handlers/postcodeSdk';
|
||||
|
||||
describe('우편번호 SDK 미확보 시 주소 입력 가능성', () => {
|
||||
let notifyFailure: ReturnType<typeof vi.fn>;
|
||||
let clearFailure: ReturnType<typeof vi.fn>;
|
||||
|
||||
/**
|
||||
* 우편번호·주소 입력 필드를 DOM 에 세웁니다.
|
||||
*
|
||||
* @return 생성된 입력 요소들
|
||||
*/
|
||||
function mountFields(): HTMLInputElement[] {
|
||||
return ['zipcode', 'address'].map(name => {
|
||||
const input = document.createElement('input');
|
||||
input.name = name;
|
||||
document.body.appendChild(input);
|
||||
|
||||
return input;
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
notifyFailure = vi.fn();
|
||||
clearFailure = vi.fn();
|
||||
(window as any).G7Core = {
|
||||
assets: { notifyFailure, clearFailure },
|
||||
};
|
||||
delete (window as any).daum;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
delete (window as any).G7Core;
|
||||
delete (window as any).daum;
|
||||
vi.restoreAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
/**
|
||||
* @scenario asset_class=service_sdk, outcome=loaded
|
||||
* @effects runtime_asset_served_same_origin
|
||||
*/
|
||||
it('SDK 가 확보되면 종전대로 읽기 전용을 적용한다', async () => {
|
||||
(window as any).daum = { Postcode: function () {} };
|
||||
const inputs = mountFields();
|
||||
|
||||
await setFieldReadOnlyHandler(
|
||||
{ handler: 'setFieldReadOnly', params: { fields: ['zipcode', 'address'], readOnly: true } },
|
||||
{} as any
|
||||
);
|
||||
|
||||
expect(inputs.every(input => input.readOnly)).toBe(true);
|
||||
expect(inputs.every(input => input.classList.contains('readonly'))).toBe(true);
|
||||
expect(notifyFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('SDK 를 끝내 못 불러오면 읽기 전용을 걸지 않고 안내를 띄운다', async () => {
|
||||
const inputs = mountFields();
|
||||
|
||||
// 대기 예산을 짧게 줘서 "끝내 안 왔다" 상태를 즉시 만든다
|
||||
await setFieldReadOnlyHandler(
|
||||
{
|
||||
handler: 'setFieldReadOnly',
|
||||
params: { fields: ['zipcode', 'address'], readOnly: true, sdkWaitMs: 150 },
|
||||
},
|
||||
{} as any
|
||||
);
|
||||
|
||||
expect(inputs.some(input => input.readOnly)).toBe(false);
|
||||
expect(notifyFailure).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [failure] = notifyFailure.mock.calls[0];
|
||||
|
||||
expect(failure.id).toBe('daum-postcode-sdk');
|
||||
expect(typeof failure.retry).toBe('function');
|
||||
});
|
||||
|
||||
it('읽기 전용 해제는 SDK 를 기다리지 않는다 (해제는 언제나 안전)', async () => {
|
||||
const inputs = mountFields();
|
||||
inputs.forEach(input => {
|
||||
input.readOnly = true;
|
||||
input.classList.add('readonly');
|
||||
});
|
||||
|
||||
await setFieldReadOnlyHandler(
|
||||
{ handler: 'setFieldReadOnly', params: { fields: ['zipcode', 'address'], readOnly: false } },
|
||||
{} as any
|
||||
);
|
||||
|
||||
expect(inputs.some(input => input.readOnly)).toBe(false);
|
||||
expect(inputs.some(input => input.classList.contains('readonly'))).toBe(false);
|
||||
expect(notifyFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('SDK 확보 판정', () => {
|
||||
it('전역이 없으면 미확보', () => {
|
||||
expect(isPostcodeSdkReady()).toBe(false);
|
||||
});
|
||||
|
||||
it('전역이 있으면 확보', () => {
|
||||
(window as any).daum = { Postcode: function () {} };
|
||||
|
||||
expect(isPostcodeSdkReady()).toBe(true);
|
||||
});
|
||||
|
||||
it('대기 중에 전역이 생기면 확보로 판정한다', async () => {
|
||||
const waiting = waitForPostcodeSdk(2000);
|
||||
|
||||
setTimeout(() => {
|
||||
(window as any).daum = { Postcode: function () {} };
|
||||
}, 150);
|
||||
|
||||
await expect(waiting).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('시간 안에 오지 않으면 미확보로 판정한다', async () => {
|
||||
await expect(waitForPostcodeSdk(200)).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,12 @@
|
||||
*/
|
||||
|
||||
import type { ActionContext } from '../types';
|
||||
import {
|
||||
clearPostcodeSdkFailure,
|
||||
isPostcodeSdkReady,
|
||||
notifyPostcodeSdkFailure,
|
||||
reloadPostcodeSdk,
|
||||
} from './postcodeSdk';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('DaumPostcode:OpenPostcode')) ?? {
|
||||
@@ -89,10 +95,10 @@ function convertToG7AddressEvent(daumData: any): G7AddressEvent {
|
||||
/**
|
||||
* 다음 우편번호 API를 호출하고 G7 표준 형식으로 변환하여 콜백 실행
|
||||
*/
|
||||
export function openPostcodeHandler(
|
||||
export async function openPostcodeHandler(
|
||||
action: ActionWithParams,
|
||||
context: ActionContext
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const params = action.params || {};
|
||||
const {
|
||||
callbackAction,
|
||||
@@ -122,9 +128,19 @@ export function openPostcodeHandler(
|
||||
});
|
||||
|
||||
// 다음 우편번호 API가 로드되었는지 확인
|
||||
if (!(window as any).daum?.Postcode) {
|
||||
logger.error('[openPostcode] Daum Postcode API not loaded');
|
||||
return;
|
||||
// 종전에는 로그만 남기고 조용히 끝나 버튼이 무반응이었다 — 사용자에게는 클릭이
|
||||
// 먹히지 않는 것으로만 보였고, 원인을 알 방법이 없었다.
|
||||
if (!isPostcodeSdkReady()) {
|
||||
logger.warn('[openPostcode] Daum Postcode API not loaded — retrying');
|
||||
|
||||
if (!(await reloadPostcodeSdk())) {
|
||||
logger.error('[openPostcode] Daum Postcode API unavailable');
|
||||
notifyPostcodeSdkFailure(() => openPostcodeHandler(action, context));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
clearPostcodeSdkFailure();
|
||||
}
|
||||
|
||||
const postcodeConfig: any = {
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* 다음 우편번호 SDK 확보 상태 판정
|
||||
*
|
||||
* 이 SDK 는 라이브러리가 아니라 Daum 이 운영하는 **서비스 SDK** 라 동봉할 수 없다.
|
||||
* 스크립트가 Daum 서버와 통신하므로 자체 호스팅해도 오프라인에서 동작하지 않는다.
|
||||
* 그래서 이 플러그인만은 외부 호스트 의존이 남으며, 대신 **못 불러왔을 때 주소를
|
||||
* 직접 입력할 수 있어야** 한다.
|
||||
*
|
||||
* 종전에는 그 반대였다: `setFieldReadOnly` 가 SDK 확보 여부와 무관하게 마운트 시점에
|
||||
* 우편번호·주소 필드를 읽기 전용으로 고정했고, 검색 버튼은 SDK 가 없으면 아무 반응이
|
||||
* 없었다. 둘이 겹쳐 **주소를 검색할 수도, 직접 입력할 수도 없는** 상태가 됐다 —
|
||||
* 주문을 끝낼 방법이 사라진다.
|
||||
*
|
||||
* @module postcodeSdk
|
||||
*/
|
||||
|
||||
/** SDK 스크립트 URL (manifest `trusted_script_hosts` 로 선언한 호스트) */
|
||||
export const DAUM_POSTCODE_SDK_URL = '//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js';
|
||||
|
||||
/** 레이아웃 확장이 삽입하는 스크립트 element id */
|
||||
export const DAUM_POSTCODE_SCRIPT_ID = 'daum_postcode_script';
|
||||
|
||||
/** 자산 실패 안내의 식별자 */
|
||||
const FAILURE_ID = 'daum-postcode-sdk';
|
||||
|
||||
/** SDK 확보를 기다리는 최대 시간(ms) — 코어 스크립트 로더의 재시도 예산과 맞춘다 */
|
||||
const DEFAULT_WAIT_MS = 12000;
|
||||
|
||||
/** 폴링 간격(ms) */
|
||||
const POLL_INTERVAL_MS = 100;
|
||||
|
||||
/**
|
||||
* 번역 문자열을 얻습니다.
|
||||
*
|
||||
* @param key 번역 키 (플러그인 네임스페이스 이하)
|
||||
* @param fallback 번역 엔진 부재 시 사용할 문구
|
||||
* @return string 번역된 문자열
|
||||
*/
|
||||
function t(key: string, fallback: string): string {
|
||||
const translate = (window as any)?.G7Core?.t;
|
||||
|
||||
if (typeof translate !== 'function') {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const full = `sirsoft-daum_postcode.${key}`;
|
||||
const result = translate(full);
|
||||
|
||||
return typeof result === 'string' && result !== full ? result : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* SDK 가 지금 사용 가능한지 판정합니다.
|
||||
*
|
||||
* @return bool 사용 가능하면 true
|
||||
*/
|
||||
export function isPostcodeSdkReady(): boolean {
|
||||
return Boolean((window as any).daum?.Postcode);
|
||||
}
|
||||
|
||||
/**
|
||||
* SDK 확보를 기다립니다.
|
||||
*
|
||||
* 레이아웃 `scripts[]` 로더가 비동기로 스크립트를 넣고 재시도까지 하므로, 마운트
|
||||
* 시점에 아직 없는 것은 정상이다. "지금 없다" 와 "끝내 못 왔다" 를 구분해야
|
||||
* 읽기 전용을 걸지 말지 판단할 수 있다.
|
||||
*
|
||||
* @param timeoutMs 최대 대기 시간(ms)
|
||||
* @return Promise<bool> 확보되면 true, 시간 안에 못 오면 false
|
||||
*/
|
||||
export function waitForPostcodeSdk(timeoutMs: number = DEFAULT_WAIT_MS): Promise<boolean> {
|
||||
if (isPostcodeSdkReady()) {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
|
||||
return new Promise<boolean>((resolve) => {
|
||||
const startedAt = Date.now();
|
||||
|
||||
const tick = () => {
|
||||
if (isPostcodeSdkReady()) {
|
||||
resolve(true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
resolve(false);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
setTimeout(tick, POLL_INTERVAL_MS);
|
||||
};
|
||||
|
||||
setTimeout(tick, POLL_INTERVAL_MS);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* SDK 스크립트를 다시 로드합니다.
|
||||
*
|
||||
* 코어 로더가 최종 실패하면 스크립트 element 를 제거하므로, 재시도는 새로 넣어야 한다.
|
||||
*
|
||||
* @return Promise<bool> 로드 후 SDK 가 확보되면 true
|
||||
*/
|
||||
export async function reloadPostcodeSdk(): Promise<boolean> {
|
||||
if (isPostcodeSdkReady()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
document.getElementById(DAUM_POSTCODE_SCRIPT_ID)?.remove();
|
||||
|
||||
const loadScript = (window as any)?.G7Core?.asset?.loadScript;
|
||||
|
||||
try {
|
||||
if (typeof loadScript === 'function') {
|
||||
await loadScript(
|
||||
DAUM_POSTCODE_SDK_URL,
|
||||
{ id: DAUM_POSTCODE_SCRIPT_ID },
|
||||
{ label: 'daum postcode SDK' }
|
||||
);
|
||||
} else {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.id = DAUM_POSTCODE_SCRIPT_ID;
|
||||
script.src = DAUM_POSTCODE_SDK_URL;
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error('daum postcode SDK load failed'));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
return isPostcodeSdkReady();
|
||||
}
|
||||
|
||||
/**
|
||||
* SDK 미확보를 사용자에게 알립니다.
|
||||
*
|
||||
* @param onRetry 재시도 성공 시 수행할 후속 동작
|
||||
* @return void
|
||||
*/
|
||||
export function notifyPostcodeSdkFailure(onRetry: () => void | Promise<void>): void {
|
||||
const notify = (window as any)?.G7Core?.assets?.notifyFailure;
|
||||
|
||||
const message = t(
|
||||
'postcode.error.sdk_unavailable',
|
||||
'주소 검색을 불러오지 못했습니다. 주소를 직접 입력해 주세요.'
|
||||
);
|
||||
|
||||
if (typeof notify !== 'function') {
|
||||
console.warn(`[sirsoft-daum_postcode] ${message}`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
notify({
|
||||
id: FAILURE_ID,
|
||||
label: t('postcode.search', '주소 검색'),
|
||||
message,
|
||||
retry: async () => {
|
||||
if (!(await reloadPostcodeSdk())) {
|
||||
throw new Error('[sirsoft-daum_postcode] 주소 검색을 여전히 불러올 수 없습니다.');
|
||||
}
|
||||
|
||||
await onRetry();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* SDK 미확보 안내를 해제합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
export function clearPostcodeSdkFailure(): void {
|
||||
(window as any)?.G7Core?.assets?.clearFailure?.(FAILURE_ID);
|
||||
}
|
||||
@@ -7,6 +7,11 @@
|
||||
*/
|
||||
|
||||
import type { ActionContext } from '../types';
|
||||
import {
|
||||
clearPostcodeSdkFailure,
|
||||
notifyPostcodeSdkFailure,
|
||||
waitForPostcodeSdk,
|
||||
} from './postcodeSdk';
|
||||
|
||||
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
|
||||
const logger = ((window as any).G7Core?.createLogger?.('DaumPostcode:SetFieldReadOnly')) ?? {
|
||||
@@ -22,6 +27,13 @@ interface ActionWithParams {
|
||||
fields?: string[];
|
||||
/** readOnly 값 (기본값: true) */
|
||||
readOnly?: boolean;
|
||||
/**
|
||||
* SDK 확보를 기다리는 최대 시간(ms).
|
||||
*
|
||||
* 레이아웃 `scripts[]` 로더가 비동기 + 재시도로 스크립트를 넣으므로 마운트
|
||||
* 시점에 SDK 가 없는 것은 정상이다. 기본값은 코어 로더의 재시도 예산에 맞춘다.
|
||||
*/
|
||||
sdkWaitMs?: number;
|
||||
};
|
||||
[key: string]: any;
|
||||
}
|
||||
@@ -42,10 +54,10 @@ interface ActionWithParams {
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
export function setFieldReadOnlyHandler(
|
||||
export async function setFieldReadOnlyHandler(
|
||||
action: ActionWithParams,
|
||||
_context: ActionContext
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const params = action.params || {};
|
||||
const fields = params.fields || [];
|
||||
const readOnly = params.readOnly !== false; // 기본값 true
|
||||
@@ -55,8 +67,38 @@ export function setFieldReadOnlyHandler(
|
||||
return;
|
||||
}
|
||||
|
||||
logger.log(`[setFieldReadOnly] Setting readOnly=${readOnly} for fields:`, fields);
|
||||
// 읽기 전용은 "검색으로만 입력할 수 있다" 는 뜻이므로, 검색이 실제로 가능할 때만
|
||||
// 건다. SDK 를 못 불러온 상태에서 걸면 검색도 직접 입력도 불가능해져 주문을
|
||||
// 끝낼 방법이 사라진다. 해제(readOnly=false)는 언제나 안전하므로 기다리지 않는다.
|
||||
if (readOnly) {
|
||||
const ready = await waitForPostcodeSdk(params.sdkWaitMs);
|
||||
|
||||
if (!ready) {
|
||||
logger.warn('[setFieldReadOnly] Daum Postcode SDK unavailable — leaving fields editable');
|
||||
applyReadOnly(fields, false);
|
||||
notifyPostcodeSdkFailure(() => {
|
||||
applyReadOnly(fields, true);
|
||||
clearPostcodeSdkFailure();
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
clearPostcodeSdkFailure();
|
||||
}
|
||||
|
||||
logger.log(`[setFieldReadOnly] Setting readOnly=${readOnly} for fields:`, fields);
|
||||
applyReadOnly(fields, readOnly);
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정된 필드에 readOnly 속성과 시각적 상태를 적용합니다.
|
||||
*
|
||||
* @param fields 필드명 배열
|
||||
* @param readOnly 적용할 readOnly 값
|
||||
* @return void
|
||||
*/
|
||||
function applyReadOnly(fields: string[], readOnly: boolean): void {
|
||||
// 각 필드에 대해 DOM에서 input 요소를 찾아 readOnly 설정
|
||||
fields.forEach((fieldName) => {
|
||||
// name 속성으로 input 요소 찾기
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
"selected": "Address has been selected.",
|
||||
"error": {
|
||||
"load_failed": "Failed to load postcode service.",
|
||||
"search_failed": "Address search failed."
|
||||
"search_failed": "Address search failed.",
|
||||
"sdk_unavailable": "Could not load address search. Please enter the address manually."
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
|
||||
@@ -19,7 +19,8 @@
|
||||
"selected": "주소가 선택되었습니다.",
|
||||
"error": {
|
||||
"load_failed": "우편번호 서비스를 불러오는데 실패했습니다.",
|
||||
"search_failed": "주소 검색에 실패했습니다."
|
||||
"search_failed": "주소 검색에 실패했습니다.",
|
||||
"sdk_unavailable": "주소 검색을 불러오지 못했습니다. 주소를 직접 입력해 주세요."
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
|
||||
@@ -17,7 +17,7 @@ export default defineConfig({
|
||||
|
||||
// 빌드 출력 설정
|
||||
outDir: 'dist',
|
||||
emptyOutDir: true,
|
||||
emptyOutDir: false, // 동봉 vendor 보존 — 산출물 정리는 빌드 커맨드가 한다
|
||||
|
||||
// 소스맵 생성
|
||||
// 배포용 빌드(--production)는 G7_BUILD_SOURCEMAP=0 을 주입해 소스맵을 생성하지 않는다.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
import path from 'path';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'jsdom',
|
||||
include: ['resources/js/**/*.{test,spec}.{ts,tsx}'],
|
||||
exclude: ['node_modules/', 'dist/'],
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, 'resources/js'),
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user